CONTENTS

Chapter 6. Advanced Swing

In this chapter, we continue our discussion of the Swing user interface toolkit from Volume 1. Swing is a very rich toolkit, and Volume 1 only covered basic and commonly used components. That leaves us with three significantly more complex components for lists, trees, and tables, whose exploration will occupy the bulk of this chapter. Components for styled text, in particular HTML, are internally even more complex, and we show you how to put them to practical use. We finish the chapter by covering component organizers such as tabbed panes and desktop panes with internal frames.

Lists

If you want to present a set of choices to a user, and a radio button or checkbox set consumes too much space, you can use a combo box or a list. Combo boxes were covered in Volume 1 because they are relatively simple. The JList component has many more features, and its design is similar to that of the tree and table components. For that reason, it is our starting point for the discussion of complex Swing components.

Of course, you can have lists of strings, but you can also have lists of arbitrary objects, with full control of how they appear. The internal architecture of the list component that makes this generality possible is rather elegant. Unfortunately, the designers at Sun felt that they needed to show off that elegance, rather than hiding it from the programmer who just wants to use the component. You will find that the list control is somewhat awkward to use for common cases because you need to manipulate some of the machinery that makes the general cases possible. We'll walk you through the simple and most common case, a list box of strings, and then give a more complex example that shows off the flexibility of the list component.

The JList Component

The JList component is similar to a set of check boxes or radio buttons, except that the items are placed inside a single box and are selected by clicking on the items themselves, not on buttons. If you permit multiple selection for a list box, the user can select any combination of the items in the box.

Figure 6-1 shows an admittedly silly example. The user can select the attributes for the fox, such as "quick," "brown," "hungry," "wild," and, because we ran out of attributes, "static," "private," and "final." You can, thus, have the static, final fox jump over the lazy dog.

Figure 6-1. A list box

graphics/06fig01.gif

To construct this list component, you first start out with an array of strings, then pass the array to the JList constructor:

String[] words= { "quick", "brown", "hungry", "wild", ... };
JList wordList = new JList(words);

Alternatively, you can use an anonymous array:

JList wordList = new JList(new String[]
   {"quick", "brown", "hungry", "wild", ... });

List boxes do not scroll automatically. To make a list box scroll, you must insert it into a scroll pane:

JScrollPane scrollPane = new JScrollPane(wordList);

Then, you need to add the scroll pane, not the list, into the surrounding panel.

We must admit that the separation of the list display and the scrolling mechanism is elegant in theory, but it is a pain in practice. Essentially all lists that we ever encountered needed scrolling. It seems cruel to force programmers to go through hoops in the default case, just so they can appreciate that elegance.

By default, the list component displays eight items; use the setVisibleRowCount method to change that value:

wordList.setVisibleRowCount(10); // display 10 items

By default, a user can select multiple items. This requires some knowledge of mouse technique: To add more items to a selection, press the CTRL key while clicking on each item. To select a contiguous range of items, click on the first one, then hold down the SHIFT key and click on the last one.

You can also restrict the user to a more limited selection mode with the setSelectionMode method:

wordList.setSelectionMode
   (ListSelectionModel.SINGLE_SELECTION);
   // select one item at a time
wordList.setSelectionMode
   (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
   // select one item or one range of items

You may recall from Volume 1 that the basic user interface components send out action events when the user activates them. List boxes use a different notification mechanism. Rather than listening to action events, you need to listen to list selection events. Add a list selection listener to the list component, and implement the method

public void valueChanged(ListSelectionEvent evt)

in the listener.

When the user selects items, a flurry of list selection events is generated. For example, suppose the user clicks on a new item. When the mouse button goes down, there is an event that reports a change in selection. This is a transitional event—the call

event.isAdjusting()

returns true if the selection is not yet final. Then, when the mouse button goes up, there is another event, this time with isAdjusting returning false. If you are not interested in the transitional events, then you can wait for the event for which isAdjusting is false. However, if you want to give the user instant feedback as soon as the mouse button is clicked, then you need to process all events.

Once you are notified that an event has happened, you will want to find out what items are currently selected. The getSelectedValues method returns an array of objects containing all selected items.

You need to cast each array element to a string.

Object[] values = list.getSelectedValues();
for (int i = 0; i < values.length; i++)
   do something with (String)values[i];

CAUTION

graphics/caution.gif
 

You cannot cast the return value of getSelectedValues from an Object[] array to a String[] array. The return value was not created as an array of strings, but as an array of objects, each of which happens to be a string. If you want to process the return value as an array of strings, you can use the following code:

int length = values.length;
String[] words = new String[length];
System.arrayCopy(values, 0, words, 0, length);

If your list does not allow multiple selections, you can call the convenience method getSelectedValue. It returns the first selected value (which you know to be the only value if multiple selections are disallowed).

String selection = (String)source.getSelectedValue();

NOTE

graphics/note.gif
 

List components do not react to double clicks from a mouse. As envisioned by the designers of Swing, you use a list to select an item, and then you need to click a button to make something happen. However, some user interfaces allow a user to double-click on a list to indicate selection of a list item and acceptance of an action. We don't think this is a good user interface style because it is difficult for users to discover that they are supposed to double-click. But if you do want to implement this behavior, you have to add a mouse listener to the list box, then trap the mouse event as follows:

public void mouseClicked(MouseEvent evt)
{
   if (evt.getClickCount() == 2)
   {
      JList source = (JList)evt.getSource();
      Object[] selection = source.getSelectedValues();
      doAction(selection);
   }
}

Example 6-1 is the listing of the program that demonstrates a list box filled with strings. Notice how the valueChanged method builds up the message string from the selected items.

Example 6-1 ListTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import javax.swing.*;
 4. import javax.swing.event.*;
 5.
 6. /**
 7.    This program demonstrates a simple fixed list of strings.
 8. */
 9. public class ListTest
10. {
11.    public static void main(String[] args)
12.    {
13.       JFrame frame = new ListFrame();
14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.       frame.show();
16.    }
17. }
18.
19. /**
20.    This frame contains a word list and a label that shows a
21.    sentence made up from the chosen words. Note that you can
22.    select multiple words with Ctrl+click and Shift+click.
23. */
24. class ListFrame extends JFrame
25. {
26.    public ListFrame()
27.    {
28.       setTitle("ListTest");
29.       setSize(WIDTH, HEIGHT);
30.
31.       String[] words =
32.       {
33.          "quick","brown","hungry","wild","silent",
34.          "huge","private","abstract","static","final"
35.       };
36.
37.       wordList = new JList(words);
38.       JScrollPane scrollPane = new JScrollPane(wordList);
39.
40.       JPanel p = new JPanel();
41.       p.add(scrollPane);
42.       wordList.addListSelectionListener(new
43.          ListSelectionListener()
44.          {
45.             public void valueChanged(ListSelectionEvent event)
46.             {
47.                Object[] values = wordList.getSelectedValues();
48.
49.                StringBuffer text = new StringBuffer(prefix);
50.                for (int i = 0; i < values.length; i++)
51.                {
52.                   String word = (String)values[i];
53.                   text.append(word);
54.                   text.append(" ");
55.                }
56.                text.append(suffix);
57.
58.                label.setText(text.toString());
59.             }
60.          });
61.
62.       Container contentPane = getContentPane();
63.       contentPane.add(p, BorderLayout.SOUTH);
64.       label = new JLabel(prefix + suffix);
65.       contentPane.add(label, BorderLayout.CENTER);
66.    }
67.
68.    private static final int WIDTH = 400;
69.    private static final int HEIGHT = 300;
70.    private JList wordList;
71.    private JLabel label;
72.    private String prefix = "The ";
73.    private String suffix = "fox jumps over the lazy dog.";
74. }
javax.swing.JList

graphics/api.gif
 

javax.swing.event.ListSelectionListener

graphics/api.gif
 

List Models

In the preceding section, you have seen the most common method for using a list component:

In the remainder of the section on lists, we will cover more complex situations that require a bit more finesse:

In the first example, we constructed a JList component that held a fixed collection of strings. However, the collection of choices in a list box is not always fixed. How do we add or remove items in the list box? Somewhat surprisingly, there are no methods in the JList class to achieve this. Instead, you have to understand a little more about the internal design of the list component. As with text components, the list component uses the model-view-controller design pattern to separate the visual appearance (a column of items that are rendered in some way) from the underlying data (a collection of objects).

The JList class is responsible for the visual appearance of the data. It actually knows very little about how the data is stored—all it knows is that it can retrieve the data through some object that implements the ListModel interface:

public interface ListModel
{
   public int getSize();
   public Object getElementAt(int i);
   public void addListDataListener(ListDataListener l);
   public void removeListDataListener(ListDataListener l);
}

Through this interface, the JList can get a count of elements and retrieve each one of the elements. Also, the JList object can add itself as a list data listener. It then gets notified if the collection of elements changes, so that it can repaint the list.

Why is this generality useful? Why doesn't the JList object simply store a vector of objects?

Note that the interface doesn't specify how the objects are stored. In particular, it doesn't force them to be stored at all! The getElementAt method is free to recompute each value whenever it is called. This is potentially useful if you want to show a very large collection without having to store the values.

Here is a somewhat silly example: we let the user choose among all three-letter words in a list box (see Figure 6-2).

Figure 6-2. Choosing from a very long list of selections

graphics/06fig02.gif

There are 26 26 26 = 17,576 three-letter combinations. Rather than storing all these combinations, we recompute them as requested when the user scrolls through them.

This turns out to be easy to implement. The tedious part, adding and removing listeners, has been done for us in the AbstractListModel class which we extend. We only need to supply the getSize and getElementAt methods:

class WordListModel extends AbstractListModel
{
   public WordListModel(int n) { length = n; }
   public int getSize() { return (int)Math.pow(26, length); }
   public Object getElementAt(int n)
   {
      // compute nth string
      . . .
   }
   . . .
}

The computation of the nth string is a bit technical—you'll find the details in the code listing in Example 6-2.

Now that we supplied a model, we can simply build a list that lets the user scroll through the elements supplied by the model:

JList wordList = new JList(new WordListModel(3));
wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(wordList);

The point is that the strings are never stored. Only those strings that the user actually requests to see are generated.

There is one other setting that we must make. We must tell the list component that all items have a fixed width and height:

wordList.setFixedCellWidth(50);
wordList.setFixedCellHeight(15);

Otherwise, the list component would compute each item to measure its width and height. That would take a long time.

As a practical matter, such very long lists are rarely useful. It is extremely cumbersome for a user to scroll through a huge selection. For that reason, we believe that the list control has been completely over-engineered. A selection that a user can comfortably manage on the screen is certainly small enough to be stored directly in the list component. That arrangement would have saved programmers from the pain of having to deal with the list model as a separate entity. On the other hand, the JList class is consistent with the JTree and JTable class where this generality is useful.

Example 6-2 LongListTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.event.*;
  5.
  6.
  7. /**
  8.    This program demonstrates a list that dynamically computes
  9.    list entries.
 10. */
 11. public class LongListTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new LongListFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19.}
 20.
 21. /**
 22.    This frame contains a long word list and a label that shows a
 23.    sentence made up from the chosen word.
 24. */
 25. class LongListFrame extends JFrame
 26. {
 27.    public LongListFrame()
 28.    {
 29.       setTitle("LongListTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       wordList = new JList(new WordListModel(3));
 33.       wordList.setSelectionMode
 34.          (ListSelectionModel.SINGLE_SELECTION);
 35.
 36.       wordList.setFixedCellWidth(50);
 37.       wordList.setFixedCellHeight(15);
 38.
 39.       JScrollPane scrollPane = new JScrollPane(wordList);
 40.
 41.       JPanel p = new JPanel();
 42.       p.add(scrollPane);
 43.       wordList.addListSelectionListener(new
 44.          ListSelectionListener()
 45.          {
 46.             public void valueChanged(ListSelectionEvent evt)
 47.             {
 48.                StringBuffer word
 49.                   = (StringBuffer)wordList.getSelectedValue();
 50.                setSubject(word.toString());
 51.             }
 52.
 53.          });
 54.
 55.       Container contentPane = getContentPane();
 56.       contentPane.add(p, BorderLayout.SOUTH);
 57.       label = new JLabel(prefix + suffix);
 58.       contentPane.add(label, BorderLayout.CENTER);
 59.       setSubject("fox");
 60.    }
 61.
 62.    /**
 63.       Sets the subject in the label.
 64.       @param word the new subject that jumps over the lazy dog
 65.    */
 66.    public void setSubject(String word)
 67.    {
 68.       StringBuffer text = new StringBuffer(prefix);
 69.       text.append(word);
 70.       text.append(suffix);
 71.       label.setText(text.toString());
 72.    }
 73.
 74.    private static final int WIDTH = 400;
 75.    private static final int HEIGHT = 300;
 76.    private JList wordList;
 77.    private JLabel label;
 78.    private String prefix = "The quick brown ";
 79.    private String suffix = " jumps over the lazy dog.";
 80.}
 81.
 82. /**
 83.    A model that dynamically generates n-letter words.
 84. */
 85. class WordListModel extends AbstractListModel
 86. {
 87.    /**
 88.       Constructs the model.
 89.       @param n the word length
 90.    */
 91.    public WordListModel(int n) { length = n; }
 92.
 93.    public int getSize()
 94.    {
 95.       return (int)Math.pow(LAST - FIRST + 1, length);
 96.    }
 97.
 98.    public Object getElementAt(int n)
 99.    {
100.       StringBuffer r = new StringBuffer();;
101.       for (int i = 0; i < length; i++)
102.       {
103.          char c = (char)(FIRST + n % (LAST - FIRST + 1));
104.          r.insert(0, c);
105.          n = n / (LAST - FIRST + 1);
106.       }
107.       return r;
108.    }
109.
110.    private int length;
111.    public static final char FIRST = 'a';
112.    public static final char LAST = 'z';
113.}
javax.swing.JList

graphics/api.gif
 

javax.swing.ListModel

graphics/api.gif
 

Inserting and Removing Values

You cannot directly edit the collection of list values. Instead, you must access the model and then add or remove elements. That, too, is easier said than done. Suppose you want to add more values to a list. You can obtain a reference to the model:

ListModel model = list.getModel();

But that does you no good—as you saw in the preceding section, the ListModel interface has no methods to insert or remove elements since, after all, the whole point of having a list model is that it need not store the elements.

Let's try it the other way around. One of the constructors of JList takes a vector of objects:

Vector values = new Vector();
values.addElement("quick");
values.addElement("brown");
. . .
JList list = new JList(values);

Of course, you can now edit the vector and add or remove elements, but the list does not know that this is happening, so it cannot react to the changes. In particular, the list cannot update its view when you add the values.

NOTE

graphics/note.gif
 

There is no JList constructor that takes an ArrayList parameter. But, since construction from a Vector isn't all that useful, that's not a real limitation.

Instead, you have to construct a particular model, the DefaultListModel, fill it with the initial values, and associate it with the list.

DefaultListModel model = new DefaultListModel();
model.addElement("quick");
model.addElement("brown");
. . .
JList list = new JList(model);

Now you can add or remove values from the model object. The model object then notifies the list of the changes, and the list repaints itself.

model.removeElement("quick");
model.addElement("slow");

As you can see, the DefaultListModel class doesn't uses the same method names as the collection classes.

The default list model uses a vector internally to store the values. It inherits the list notification mechanism from AbstractListModel, just as the example model class of the preceding section.

CAUTION

graphics/caution.gif
 

There are JList constructors that construct a list from an array or vector of objects or strings. You might think that these constructors use a DefaultListModel to store these values. That is not the case—the constructors build a trivial model that can access the values without any provisions for notification if the contents changes. For example, here is the code for the constructor that constructs a JList from a Vector:

public JList(final Vector listData)
{
   this (new AbstractListModel()
   {
      public int getSize() { return listData.size(); }
      public Object getElementAt(int i)
      { return listData.elementAt(i); }
   });
}

That means, if you change the contents of the vector after the list is constructed, then the list may show a confusing mix of old and new values until it is completely repainted. (The keyword final in the constructor above does not prevent you from changing the vector elsewhere—it only means that the constructor itself won't modify the value of the listData reference; the keyword is required because the listData object is used in the inner class.)

javax.swing.JList

graphics/api.gif
 

javax.swing.DefaultListModel

graphics/api.gif
 

Rendering Values

So far, all lists that you saw in this chapter contained only strings. It is actually just as easy to show a list of icons—simply pass an array or vector filled with Icon objects. More interestingly, you can easily represent your list values with any drawing whatsoever.

While the JList class can display strings and icons automatically, you need to install a list cell renderer into the JList object for all custom drawing. A list cell renderer is any class that implements the following interface:

interface ListCellRenderer
{
   Component getListCellRendererComponent(JList list,
      Object value, int index,
      boolean isSelected, boolean cellHasFocus);
}

If you install a list cell renderer into a list, it gets called for each list value: first, if you did not select fixed-sized cells, to measure the size of the graphical representation of the value; then, to draw it. You must provide a class that returns an object of type Component, such that the getPreferredSize and paint methods of the returned object carry out these tasks as appropriate for your list values.

A simple way to do this is to create an inner class with these two methods:

class MyCellRenderer implements ListCellRenderer
{
   public Component getListCellRendererComponent(final JList list,
      final Object value, final int index,
      final boolean isSelected, final boolean cellHasFocus)
   {
      return new
         JPanel()
         {
            public void paintComponent(Graphics g)
            {
               // paint code goes here
            }
            public Dimension getPreferredSize()
            {
               // size measurement code goes here
            }
         };
   }
}

In Example 6-3, we display the font choices graphically by showing the actual appearance of each font (see Figure 6-3). In the paintComponent method, we display each name in its own font. We also need to make sure to match the usual colors of the look and feel of the JList class. We obtain these colors by calling the getForeground/getBackground and getSelectionForeground/getSelectionBackground methods of the JList class. In the getPreferredSize method, we need to measure the size of the string, using the techniques that you saw in Chapter 7 of Volume 1.

Figure 6-3. A list box with rendered cells

graphics/06fig03.gif

To install the cell renderer, simply call the setCellRenderer method:

fontList.setCellRenderer(new FontCellRenderer());

Now all list cells are drawn with the custom renderer.

There is actually a simpler method for writing custom renderers that works in many cases. If the rendered image just contains text, an icon, and possibly a change of color, then you can get by with configuring a JLabel. For example, to show the font name in its own font, we can use the following renderer:

class FontCellRenderer implements ListCellRenderer
{
   public Component getListCellRendererComponent(JList list,
      Object value, int index, boolean isSelected,
         boolean cellHasFocus)
   {
      JLabel label = new JLabel();
      Font font = (Font)value;
      label.setText(font.getFamily());
      label.setFont(font);
      label.setOpaque(true);
      label.setBackground(isSelected
         ? list.getSelectionBackground()
         : list.getBackground());
      label.setForeground(isSelected
         ? list.getSelectionForeground()
         : list.getForeground());
      return label;
   }
}

Note that here we don't write any paintComponent or getPreferredSize methods; the JLabel class already implements these methods to our satisfac-tion. All we need to do is to configure the label appropriately by setting its text, font, and color.

For added conciseness, the FontCellRenderer can even extend JLabel, configure itself with every call to getListCellRendererComponent, and then return this:

class FontCellRenderer extends JLabel implements ListCellRenderer
{
   public Component getListCellRendererComponent(JList list,
      Object value, int index, boolean isSelected,
         boolean cellHasFocus)
   {
      Font font = (Font)value;
      setText(font.getFamily());
      setFont(font);
      setOpaque(true);
      setBackground(isSelected
         ? list.getSelectionBackground()
         : list.getBackground());
      setForeground(isSelected
         ? list.getSelectionForeground()
         : list.getForeground());
      return this;
   }
}

This code is a convenient shortcut for those cases where an existing component—in this case, JLabel—already provides all functionality that is needed to render a cell value.

Example 6-3 ListRenderingTest.java
  1. import java.util.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6.
  7. /**
  8.    This program demonstrates the use of cell renderers in
  9.    a list box.
 10. */
 11. public class ListRenderingTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new ListRenderingFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19. }
 20.
 21. /**
 22.    This frame contains a list with a set of fonts and a text
 23.    area that is set to the selected font.
 24. */
 25. class ListRenderingFrame extends JFrame
 26. {
 27.    public ListRenderingFrame()
 28.    {
 29.       setTitle("ListRenderingTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       ArrayList fonts = new ArrayList();
 33.       final int SIZE = 24;
 34.       fonts.add(new Font("Serif", Font.PLAIN, SIZE));
 35.       fonts.add(new Font("SansSerif", Font.PLAIN, SIZE));
 36.       fonts.add(new Font("Monospaced", Font.PLAIN, SIZE));
 37.       fonts.add(new Font("Dialog", Font.PLAIN, SIZE));
 38.       fonts.add(new Font("DialogInput", Font.PLAIN, SIZE));
 39.       fontList = new JList(fonts.toArray());
 40.       fontList.setVisibleRowCount(4);
 41.       fontList.setSelectionMode
 42.          (ListSelectionModel.SINGLE_SELECTION);
 43.       fontList.setCellRenderer(new FontCellRenderer());
 44.       JScrollPane scrollPane = new JScrollPane(fontList);
 45.
 46.       JPanel p = new JPanel();
 47.       p.add(scrollPane);
 48.       fontList.addListSelectionListener(new
 49.          ListSelectionListener()
 50.          {
 51.             public void valueChanged(ListSelectionEvent evt)
 52.             {
 53.                Font font = (Font)fontList.getSelectedValue();
 54.                text.setFont(font);
 55.             }
 56
 57.          });
 58.
 59.       Container contentPane = getContentPane();
 60.       contentPane.add(p, BorderLayout.SOUTH);
 61.       text = new JTextArea(
 62.          "The quick brown fox jumps over the lazy dog");
 63.       text.setFont((Font)fonts.get(0));
 64.       text.setLineWrap(true);
 65.       text.setWrapStyleWord(true);
 66.       contentPane.add(text, BorderLayout.CENTER);
 67.    }
 68
 69.    private JTextArea text;
 70.    private JList fontList;
 71.    private static final int WIDTH = 400;
 72.    private static final int HEIGHT = 300;
 73. }
 74.
 75. /**
 76.    A cell renderer for Font objects that renders the font name
 77.    in its own font.
 78. */
 79. class FontCellRenderer implements ListCellRenderer
 80. {
 81.    public Component getListCellRendererComponent
 82.       (final JList list, final Object value,
 83.       final int index, final boolean isSelected,
 84.       final boolean cellHasFocus)
 85.    {
 86.       return new
 87.          JPanel()
 88.          {
 89.             public void paintComponent(Graphics g)
 90.             {
 91.                Font font = (Font)value;
 92.                String text = font.getFamily();
 93.                FontMetrics fm = g.getFontMetrics(font);
 94.                g.setColor(isSelected
 95.                   ? list.getSelectionBackground()
 96.                   : list.getBackground());
 97.                g.fillRect(0, 0, getWidth(), getHeight());
 98.                g.setColor(isSelected
 99.                   ? list.getSelectionForeground()
100                    : list.getForeground());
101.                g.setFont(font);
102.                g.drawString(text, 0, fm.getAscent());
103.             }
104.
105.            public Dimension getPreferredSize()
106.            {
107.               Font font = (Font)value;
108.               String text = font.getFamily();
109.               Graphics g = getGraphics();
110.               FontMetrics fm = g.getFontMetrics(font);
111.               return new Dimension(fm.stringWidth(text),
112.                  fm.getHeight());
113.            }
114.         };
115.    }
116.}
javax.swing.JList

graphics/api.gif
 

javax.swing.ListCellRenderer

graphics/api.gif
 

Trees

Every computer user who uses a hierarchical file system has encountered tree displays such as the one in Figure 6-4. Of course, directories and files form only one of the many examples of treelike organizations. Programmers are familiar with inheritance trees for classes. There are many tree structures that arise in everyday life, such as the hierarchy of countries, states, and cities shown in Figure 6-5.

Figure 6-4. A directory tree

graphics/06fig04.gif
 

Figure 6-5. A hierarchy of countries, states, and cities

graphics/06fig05.gif

As programmers, we often have to display these tree structures. Fortunately, the Swing library has a JTree class for this purpose. The JTree class (together with its helper classes) takes care of laying out the tree and of processing user requests for expanding and collapsing nodes. In this section, you will learn how to put the JTree class to use. As with the other complex Swing components, we must focus on the common and useful cases and cannot cover every nuance—we recommend that you consult Core Java Foundation Classes by Kim Topley [Prentice-Hall 1998] or Graphic Java 2 by David M. Geary [Prentice-Hall 1999] if you want to achieve an unusual effect.

Before going any further, let's settle on some terminology (see Figure 6-6). A tree is composed of nodes. Every node is either a leaf, or it has child nodes. Every node, with the exception of the root node, has exactly one parent. A tree has exactly one root node. Sometimes you have a collection of trees, each of which has its own root node. Such a collection is called a forest.

Figure 6-6. Tree terminology

graphics/06fig06.gif

Simple Trees

In our first example program, we simply display a tree with a few nodes (see Figure 6-8). As with most other Swing components, the JTree component follows the model/view/controller pattern. You provide a model of the hierarchical data, and the component displays it for you. To construct a JTree, you supply the tree model in the constructor:

Figure 6-8. A simple tree

graphics/06fig08.gif

TreeModel model = . . .;
JTree tree = new JTree(model);

NOTE

graphics/note.gif
 

There are also constructors that construct trees out of a collection of elements:

JTree(Object[] nodes)
JTree(Vector nodes)
JTree(Hashtable nodes) // the values become the nodes

These constructors are not very useful. They merely build a forest of trees, each with a single node. The third constructor seems particularly useless since the nodes appear in the essentially random order given by the hash codes of the keys.

How do you obtain a tree model? You can construct your own model by creating a class that implements the TreeModel interface. You will see later in this chapter how to do that. For now, we'll stick with the DefaultTreeModel that the Swing library supplies.

To construct a default tree model, you must supply a root node.

TreeNode root = . . .;
DefaultTreeModel model = new DefaultTreeModel(root);

TreeNode is another interface. You populate the default tree model with objects of any class that implements the interface. For now, we will use the concrete node class that Swing supplies, namely DefaultMutableTreeNode. This class implements the MutableTreeNode interface, a subinterface of TreeNode (see Figure 6-7).

Figure 6-7. Tree classes

graphics/06fig07.gif

A default mutable tree node holds an object, the user object. The tree renders the user objects for all nodes. Unless you specify a renderer, the tree simply displays the string that is the result of the toString method.

In our first example, we use strings as user objects. In practice, you would usually populate a tree with more expressive user objects. For example, when displaying a directory tree, it makes sense to use File objects for the nodes.

You can specify the user object in the constructor, or you can set it later with the setUserObject method.

DefaultMutableTreeNode node
   = new DefaultMutableTreeNode("Texas");
node.setUserObject("California");

Next, you establish the parent/child relationships between the nodes. Start with the root node, and use the add method to add the children:

DefaultMutableTreeNode root
   = new DefaultMutableTreeNode("World");
DefaultMutableTreeNode country
   = new DefaultMutableTreeNode("USA");
root.add(country);
DefaultMutableTreeNode state
   = new DefaultMutableTreeNode("California");
country.add(state);

Figure 6-8 illustrates how the tree will look.

Link up all nodes in this fashion. Then, construct a DefaultTreeModel with the root node. Finally, construct a JTree with the tree model.

DefaultTreeModel treeModel = new DefaultTreeModel(root);
JTree tree = new JTree(treeModel);

Or, as a shortcut, you can simply pass the root node to the JTree constructor. Then the tree automatically constructs a default tree model:

JTree tree = new JTree(root);

Example 6-4 contains the complete code.

Example 6-4 SimpleTree.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import javax.swing.*;
 4. import javax.swing.tree.*;
 5.
 6. /**
 7.    This program shows a simple tree.
 8. */
 9. public class SimpleTree
10. {
11.    public static void main(String[] args)
12.    {
13.       JFrame frame = new SimpleTreeFrame();
14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.       frame.show();
16.    }
17. }
18.
19. /**
20.    This frame contains a simple tree that displays a
21.    manually constructed tree model.
22. */
23. class SimpleTreeFrame extends JFrame
24. {
25.    public SimpleTreeFrame()
26.    {
27.       setTitle("SimpleTree");
28.       setSize(WIDTH, HEIGHT);
29.
30.       // set up tree model data
31.
32.       DefaultMutableTreeNode root
33.          = new DefaultMutableTreeNode("World");
34.       DefaultMutableTreeNode country
35.          = new DefaultMutableTreeNode("USA");
36.       root.add(country);
37.       DefaultMutableTreeNode state
38.          = new DefaultMutableTreeNode("California");
39.       country.add(state);
40.       DefaultMutableTreeNode city
41.          = new DefaultMutableTreeNode("San Jose");
42.       state.add(city);
43.       city = new DefaultMutableTreeNode("Cupertino");
44.       state.add(city);
45.       state = new DefaultMutableTreeNode("Michigan");
46.       country.add(state);
47.       city = new DefaultMutableTreeNode("Ann Arbor");
48.       state.add(city);
49.       country = new DefaultMutableTreeNode("Germany");
50.       root.add(country);
51.       state = new DefaultMutableTreeNode("Schleswig-Holstein");
52.       country.add(state);
53.       city = new DefaultMutableTreeNode("Kiel");
54.       state.add(city);
55.
56.       // construct tree and put it in a scroll pane
57.
58.       JTree tree = new JTree(root);
59.       Container contentPane = getContentPane();
60.       contentPane.add(new JScrollPane(tree));
61.    }
62.
63.    private static final int WIDTH = 300;
64.    private static final int HEIGHT = 200;
65. }

When you run the program, the tree first looks as in Figure 6-9. Only the root node and its children are visible. Click on the circle icons (the handles) to open up the subtrees. The line sticking out from the handle icon points to the right when the subtree is collapsed, and it points down when the subtree is expanded (see Figure 6-10). We don't know what the designers of the Metal look and feel had in mind, but we think of the icon as a door handle. You push down on the handle to open the subtree.

Figure 6-9. The initial tree display

graphics/06fig09.gif

Figure 6-10. Collapsed and expanded subtrees

graphics/06fig10.gif

NOTE

graphics/note.gif
 

Of course, the display of the tree depends on the selected look and feel. We just described the Java look and feel (a.k.a. "Metal"). In the Windows and Motif look and feel, the handles have the more familiar look—a "+" or "-" in a box (see Figure 6-11).

Figure 6-11. A tree with the Windows look and feel

graphics/06fig11.gif
 

Up to SDK 1.3, the Java look and feel does not display the tree outline by default (see Figure 6-12). As of SDK 1.4, the default line style is "angled."

Figure 6-12. A tree with no connecting lines

graphics/06fig12.gif

In SDK 1.4, use the following magic incantation to turn off the lines joining parents and children:

tree.putClientProperty("JTree.lineStyle", "None");

Conversely, to make sure that the angled lines are shown, use

tree.putClientProperty("JTree.lineStyle", "Angled");

There is also another line style, "Horizontal", that is shown in Figure 6-13. The tree is displayed with horizontal lines separating only the children of the root. We aren't quite sure what it is good for.

Figure 6-13. A tree with the horizontal line style

graphics/06fig13.gif

By default, there is no handle for collapsing the root of the tree. If you like, you can add one with the call

tree.setShowsRootHandles(true);

Figure 6-14 shows the result. Now you can collapse the entire tree into the root node.

Figure 6-14. A tree with a root handle

graphics/06fig14.gif

Conversely, you can hide the root altogether. You do that to display a forest, a set of trees, each of which has its own root. You still must join all trees in the forest to a common root. Then, you hide the root with the instruction

tree.setRootVisible(false);

Look at Figure 6-15. There appear to be two roots, labeled "USA" and "Germany." The actual root that joins the two is made invisible.

Figure 6-15. A forest

graphics/06fig15.gif

Let's turn from the root to the leaves of the tree. Note that the leaves have a different icon than the other nodes (see Figure 6-16).

Figure 6-16. Leaf icons

graphics/06fig16.gif

When displaying the tree, each node is drawn with an icon. There are actually three kinds of icons: a leaf icon, an opened non-leaf icon, and a closed non-leaf icon. For simplicity, we'll refer to the last two as folder icons.

The node renderer needs to know which icon to use for each node. By default, the decision process works like this: If the isLeaf method of a node returns true, then the leaf icon is used. Otherwise, a folder icon is used.

The isLeaf method of the DefaultMutableTreeNode class returns true if the node has no children. Thus, nodes with children get folder icons, and nodes without children get leaf icons.

Sometimes, that behavior is not appropriate. Suppose we added a node "Montana" to our sample tree, but we're at a loss as to what cities to add. We would not want the state node to get a leaf icon since conceptually only the cities are leaves.

The JTree class has no idea which nodes should be leaves. It asks the tree model. If a childless node isn't automatically a conceptual leaf, you can ask the tree model to use a different criterion for leafiness, namely to query the "allows children" node property.

For those nodes that should not have children, call

node.setAllowsChildren(false);

Then, tell the tree model to ask the value of the "allows children" property to determine whether a node should be displayed with a leaf icon. You use the setAsksAllowsChildren method of the DefaultTreeModel class to set this behavior:

model.setAsksAllowsChildren(true);

With this decision criterion, nodes that allow children get folder icons, and nodes that don't allow children get leaf icons.

Alternatively, if you construct the tree by supplying the root node, supply the setting for the "asks allows children" property in the constructor.

JTree tree = new JTree(root, true);
   // nodes that don't allow children get leaf icons
javax.swing.JTree

graphics/api.gif
 

javax.swing.tree.TreeNode

graphics/api.gif
 

javax.swing.tree.MutableTreeNode

graphics/api.gif
 

javax.swing.tree.TreeModel

graphics/api.gif
 

javax.swing.tree.DefaultTreeModel

graphics/api.gif
 

javax.swing.tree.DefaultMutableTreeNode

graphics/api.gif
 

javax.swing.JComponent

graphics/api.gif
 

Editing trees and tree paths

In the next example program, you will see how to edit a tree. Figure 6-17 shows the user interface. If you click on the "Add Sibling" or "Add Child" button, the program adds a new node (with title New) to the tree. If you click on the "Delete" button, the program deletes the currently selected node.

Figure 6-17. Editing a tree

graphics/06fig17.gif

To implement this behavior, you need to find out which tree node is currently selected. The JTree class has a surprising way of identifying nodes in a tree. It does not deal with tree nodes, but with paths of objects, called tree paths. A tree path starts at the root and consists of a sequence of child nodes—see Figure 6-18.

Figure 6-18. A tree path

graphics/06fig18.gif

You may wonder why the JTree class needs the whole path. Couldn't it just get a TreeNode and keep calling the getParent method? In fact, the JTree class knows nothing about the TreeNode interface. That interface is never used by the TreeModel interface; it is only used by the DefaultTreeModel implementation. You can have other tree models in which the nodes do not implement the TreeNode interface at all. If you use a tree model that manages other types of objects, then those objects may not have getParent and getChild methods. They would of course need to have some other connection to each other. It is the job of the tree model to link nodes together. The JTree class itself has no clue about the nature of their linkage. For that reason, the JTree class always needs to work with complete paths.

The TreePath class manages a sequence of Object (not TreeNode!) references. A number of JTree methods return TreePath objects. When you have a tree path, you usually just need to know the terminal node, which you get with the getLastPathComponent method. For example, to find out the currently selected node in a tree, you use the getSelectionPath method of the JTree class. You get a TreePath object back, from which you can retrieve the actual node.

TreePath selectionPath = tree.getSelectionPath();
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
   selectionPath.getLastPathComponent();

Actually, because this particular query is so common, there is a convenience method that gives the selected node immediately.

DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
   tree.getLastSelectedPathComponent();

This method is not called getSelectedNode because the tree does not know that it contains nodes—its tree model only deals with paths of objects.

NOTE

graphics/note.gif
 

Tree paths are one of two ways that the JTree class uses to describe nodes. There are also quite a few JTree methods that take or return an integer index, the row position. A row position is simply the row number (starting with 0) of the node in the tree display. Only visible nodes have row numbers, and the row number of a node changes if other nodes before it are expanded, collapsed, or modified. For that reason, you should avoid row positions. All JTree methods that use rows have equivalents that use tree paths instead.

Once you have the selected node, you can edit it. However, do not simply add children to a tree node:

selectedNode.add(newNode); // NO!

If you change the structure of the nodes, you change the model but the associated view is not notified. You could send out a notification yourself, but if you use the insertNodeInto method of the DefaultTreeModel class, the model class takes care of that. For example, the following call appends a new node as the last child of the selected node and notifies the tree view.

model.insertNodeInto(newNode, selectedNode,
   selectedNode.getChildCount());

The analogous call removeNodeFromParent removes a node and notifies the view:

model.removeNodeFromParent(selectedNode);

If you keep the node structure in place but you changed the user object, you should call the following method:

model.nodeChanged(changedNode);

The automatic notification is a major advantage of using the DefaultTreeModel. If you supply your own tree model, you have to implement it by hand. (See Core Java Foundation Classes by Kim Topley for details.)

CAUTION

graphics/caution.gif
 

The DefaultTreeModel class has a reload method that reloads the entire model. However, don't call reload simply to update the tree after making a few changes. When the tree is regenerated, all nodes beyond the root's children are collapsed again. It is quite disconcerting to your users if they have to keep expanding the tree after every change.

When the view is notified of a change in the node structure, it updates the display but it does not automatically expand a node to show newly added children. In particular, if a user in our sample program adds a new child node to a node whose children are currently collapsed, then the new node is silently added to the collapsed subtree. This gives the user no feedback that the command was actually carried out. In such a case, you should make a special effort to expand all parent nodes so that the newly added node becomes visible. You use the makeVisible method of the JTree class for this purpose. The makeVisible method expects a tree path leading to the node that should become visible.

Thus, you need to construct a tree path from the root to the newly inserted node. To get a tree path, you first call the getPathToRoot method of the DefaultTreeModel class. It returns a TreeNode[] array of all nodes from a node to the root node. You pass that array to a TreePath constructor.

For example, here is how you make the new node visible:

TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
tree.makeVisible(path);

NOTE

graphics/note.gif
 

It is curious that the DefaultTreeModel class feigns almost complete ignorance about the TreePath class, even though its job is to communicate with a JTree. The JTree class uses tree paths a lot, and it never uses arrays of node objects.

But now suppose your tree is contained inside a scroll pane. After the tree node expansion, the new node may still not be visible because it falls outside the viewport. To overcome that problem, call

tree.scrollPathToVisible(path);

instead of calling makeVisible. This call expands all nodes along the path, and it tells the ambient scroll pane to scroll the node at the end of the path into view (see Figure 6-19).

Figure 6-19. The scroll pane scrolls to display a new node

graphics/06fig19.gif

By default, tree nodes cannot be edited. However, if you call

tree.setEditable(true);

then the user can edit a node simply by double-clicking, editing the string, and pressing the ENTER key. Double-clicking invokes the default cell editor, which is implemented by the DefaultCellEditor class (see Figure 6-20). It is possible to install other cell editors, but we will defer our discussion of cell editors until the section on tables, where cell editors are more commonly used.

Figure 6-20. The Default Cell Editor

graphics/06fig20.gif

Example 6-5 shows the complete source code of the tree editing program. Run the program, add a few nodes, and edit them by double-clicking them. Observe how collapsed nodes expand to show added children and how the scroll pane keeps added nodes in the viewport.

Example 6-5 TreeEditTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.tree.*;
  5.
  6. /**
  7.    This program demonstrates tree editing.
  8. */
  9. public class TreeEditTest
 10. {
 11.    public static void main(String[] args)
 12.    {
 13.       JFrame frame = new TreeEditFrame();
 14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 15.       frame.show();
 16.    }
 17. }
 18.
 19. /**
 20.    A frame with a tree and buttons to edit the tree.
 21. */
 22. class TreeEditFrame extends JFrame
 23. {
 24.    public TreeEditFrame()
 25.    {
 26.       setTitle("TreeEditTest");
 27.       setSize(WIDTH, HEIGHT);
 28.
 29.       // construct tree
 30.
 31.       TreeNode root = makeSampleTree();
 32.       model = new DefaultTreeModel(root);
 33.       tree = new JTree(model);
 34.       tree.setEditable(true);
 35.
 36.       // add scroll pane with tree to content pane
 37.
 38.       JScrollPane scrollPane = new JScrollPane(tree);
 39.       getContentPane().add(scrollPane, BorderLayout.CENTER);
 40.
 41.       makeButtons();
 42.       // make button panel
 43.
 44.    }
 45.
 46.    public TreeNode makeSampleTree()
 47.    {
 48.       DefaultMutableTreeNode root
 49.          = new DefaultMutableTreeNode("World");
 50.       DefaultMutableTreeNode country
 51.          = new DefaultMutableTreeNode("USA");
 52.       root.add(country);
 53.       DefaultMutableTreeNode state
 54.          = new DefaultMutableTreeNode("California");
 55.       country.add(state);
 56.       DefaultMutableTreeNode city
 57.          = new DefaultMutableTreeNode("San Jose");
 58.       state.add(city);
 59.       city = new DefaultMutableTreeNode("Cupertino");
 60.       state.add(city);
 61.       state = new DefaultMutableTreeNode("Michigan");
 62.       country.add(state);
 63.       city = new DefaultMutableTreeNode("Ann Arbor");
 64.       state.add(city);
 65.       country = new DefaultMutableTreeNode("Germany");
 66.       root.add(country);
 67.       state = new DefaultMutableTreeNode("Schleswig-Holstein");
 68.       country.add(state);
 69.       city = new DefaultMutableTreeNode("Kiel");
 70.       state.add(city);
 71.       return root;
 72.    }
 73.
 74.    /**
 75.       Makes the buttons to add a sibling, add a child, and
 76.       delete a node.
 77.    */
 78.    public void makeButtons()
 79.    {
 80.       JPanel panel = new JPanel();
 81.       JButton addSiblingButton = new JButton("Add Sibling");
 82.       addSiblingButton.addActionListener(new
 83.          ActionListener()
 84.          {
 85.             public void actionPerformed(ActionEvent event)
 86.             {
 87.                DefaultMutableTreeNode selectedNode
 88.                   = (DefaultMutableTreeNode)
 89.                   tree.getLastSelectedPathComponent();
 90.
 91.                if (selectedNode == null) return;
 92.
 93.                DefaultMutableTreeNode parent
 94.                   = (DefaultMutableTreeNode)
 95.                   selectedNode.getParent();
 96.
 97.                if (parent == null) return;
 98.
 99.                DefaultMutableTreeNode newNode
100.                   = new DefaultMutableTreeNode("New");
101.
102.                int selectedIndex = parent.getIndex(selectedNode);
103.                model.insertNodeInto(newNode, parent,
104.                   selectedIndex + 1);
105.
106.                // now display new node
107.
108.                TreeNode[] nodes = model.getPathToRoot(newNode);
109.                TreePath path = new TreePath(nodes);
110.                tree.scrollPathToVisible(path);
111.             }
112.          });
113.       panel.add(addSiblingButton);
114.
115.       JButton addChildButton = new JButton("Add Child");
116.       addChildButton.addActionListener(new
117.          ActionListener()
118.          {
119.             public void actionPerformed(ActionEvent event)
120.             {
121.                DefaultMutableTreeNode selectedNode
122.                   = (DefaultMutableTreeNode)
123.                   tree.getLastSelectedPathComponent();
124.
125.                if (selectedNode == null) return;
126.
127.                DefaultMutableTreeNode newNode
128.                   = new DefaultMutableTreeNode("New");
129.                model.insertNodeInto(newNode, selectedNode,
130.                   selectedNode.getChildCount());
131.
132.                // now display new node
133.
134.                TreeNode[] nodes = model.getPathToRoot(newNode);
135.                TreePath path = new TreePath(nodes);
136.                tree.scrollPathToVisible(path);
137.             }
138.          });
139.       panel.add(addChildButton);
140.
141.       JButton deleteButton = new JButton("Delete");
142.       deleteButton.addActionListener(new
143.          ActionListener()
144.          {
145.             public void actionPerformed(ActionEvent event)
146.             {
147.                DefaultMutableTreeNode selectedNode
148.                   = (DefaultMutableTreeNode)
149.                   tree.getLastSelectedPathComponent();
150.
151.                if (selectedNode != null &&
152.                   selectedNode.getParent() != null)
153.                   model.removeNodeFromParent(selectedNode);
154.             }
155.          });
156.       panel.add(deleteButton);
157.       getContentPane().add(panel, BorderLayout.SOUTH);
158.    }
159.
160.    private DefaultTreeModel model;
161.    private JTree tree;
162.    private static final int WIDTH = 400;
163.    private static final int HEIGHT = 200;
164. }
javax.swing.JTree

graphics/api.gif
 

javax.swing.tree.TreePath

graphics/api.gif
 

javax.swing.tree.TreeNode

graphics/api.gif
 

javax.swing.DefaultTreeModel

graphics/api.gif
 

Node Enumeration

Sometimes you need to find a node in a tree by starting at the root and visiting all children until you have found a match. The DefaultMutableTreeNode class has several convenience methods for iterating through nodes.

The breadthFirstEnumeration and depthFirstEnumeration methods return enumeration objects whose nextElement method visits all children of the current node, using either a breadth-first or depth-first traversal. Figure 6-21 shows the traversals for a sample tree—the node labels indicate the order in which the nodes are traversed.

Figure 6-21. Tree traversal orders

graphics/06fig21.gif

Breadth-first enumeration is the easiest to visualize. The tree is traversed in layers. The root is visited first, followed by all of its children, then followed by the grandchildren, and so on.

To visualize depth-first enumeration, imagine a rat trapped in a tree-shaped maze. It rushes along the first path until it comes to a leaf. Then, it backtracks and turns around to the next path, and so on.

Computer science types also call this postorder traversal, because the search process first visits the children before visiting the parents. The postOrderTraversal method is a synonym for depthFirstTraversal. For completeness, there is also a preOrderTraversal, a depth-first search that enumerates parents before the children.

Here is the typical usage pattern:

Enumeration breadthFirst = node.breadthFirstEnumeration();
while (breadthFirst.hasMoreElements())
   do something with breadthFirst.nextElement();

Finally, there is a related method pathFromAncestorEnumeration that finds a path from an ancestor to a given node and then enumerates the nodes along that path. That's no big deal—it just keeps calling getParent until the ancestor is found and then presents the path in reverse order.

In our next example program, we put node enumeration to work. The program displays inheritance trees of classes. Type the name of a class into the text field on the bottom of the frame. The class and all of its superclasses are added to the tree (see Figure 6-22).

Figure 6-22. An inheritance tree

graphics/06fig22.gif

In this example, we take advantage of the fact that the user objects of the tree nodes can be objects of any type. Since our nodes describe classes, we will store Class objects in the nodes.

Of course, we don't want to add the same class object twice, so we need to check whether a class already exists in the tree. The following method finds the node with a given user object if it exists in the tree.

   public DefaultMutableTreeNode findUserObject(Object obj)
   {
      Enumeration e = root.breadthFirstEnumeration();
      while (e.hasMoreElements())
      {
         DefaultMutableTreeNode node
            = (DefaultMutableTreeNode)e.nextElement();
         if (node.getUserObject().equals(obj))
            return node;
      }
      return null;
   }

Rendering Nodes

In your applications, you will often need to change the way in which a tree component draws the nodes. The most common change is, of course, to choose different icons for nodes and leaves. Other changes might involve changing the font of the node labels or drawing images at the nodes. All these changes are made possible by installing a new tree cell renderer into the tree. By default, the JTree class uses DefaultTreeCellRenderer objects to draw each node. The DefaultTreeCellRenderer class extends the JLabel class. The label contains the node icon and the node label.

NOTE

graphics/note.gif
 

The cell renderer does not draw the "handles" for expanding and collapsing subtrees. The handles are part of the look and feel, and it is recommended that you not change them.

You can customize the display in three ways.

  1. You can change the icons, font, and background color used by a DefaultTreeCellRenderer. These settings are used for all nodes in the tree.

  2. You can install a renderer that extends the DefaultTreeCellRenderer class and vary the icons, fonts, and background color for each node.

  3. You can install a renderer that implements the TreeCellRenderer interface, to draw a custom image for each node.

Let us look at these possibilities one by one. The easiest customization is to construct a DefaultTreeCellRenderer object, change the icons, and install it into the tree:

DefaultTreeCellRenderer renderer
   = new DefaultTreeCellRenderer();
renderer.setLeafIcon(new ImageIcon("blue-ball.gif"));
   // used for leaf nodes
renderer.setClosedIcon(new ImageIcon("red-ball.gif"));
   // used for collapsed nodes
renderer.setOpenIcon(new ImageIcon("yellow-ball.gif"));
   // used for expanded nodes
tree.setCellRenderer(renderer);

You can see the effect in Figure 6-22. We just use the "ball" icons as placeholders—presumably your user interface designer would supply you with appropriate icons to use for your applications.

We don't recommend that you change the font or background color for an entire tree—that is really the job of the look and feel.

However, it can be useful to change the font for individual nodes in a tree to highlight some of them. If you look carefully at Figure 6-22, you will notice that the abstract classes are set in italics.

To change the appearance of individual nodes, you install a tree cell renderer. Tree cell renderers are very similar to the list cell renderers we discussed in Chapter 9 of Volume 1. The TreeCellRenderer interface has a single method

Component getTreeCellRendererComponent(JTree tree,
   Object value, boolean selected, boolean expanded,
   boolean leaf, int row, boolean hasFocus)

This method is called for each node. It returns a component whose paint method renders the node in the tree display. The paint method is invoked with an appropriate Graphics object, with coordinates and clip rectangle set so that the drawing appears at the correct location.

NOTE

graphics/note.gif
 

You may wonder why you don't simply get to place a paint method into the class that implements the tree cell renderer interface. There is a very good reason. It is usually easier for you to tweak existing components than to program the actual drawing code. For example, the default tree cell renderer simply extends JLabel and lets the label worry about the correct spacing between the icon and the label text.

The getTreeCellRendererComponent method of the DefaultTreeCellRenderer class returns this—in other words, a label. (Recall that the DefaultTreeCellRenderer class extends the JLabel class.) To customize the component, extend the DefaultTreeCellRenderer class. Override the getTreeCellRendererComponent method as follows: call the superclass method, so that it can prepare the label data. Customize the label properties, and finally return this.

class MyTreeCellRenderer extends DefaultTreeCellRenderer
{
   public Component getTreeCellRendererComponent(JTree tree,
      Object value, boolean selected, boolean expanded,
      boolean leaf, int row, boolean hasFocus)
   {
      super.getTreeCellRendererComponent(tree, value,
         selected, expanded, leaf, row, hasFocus);
      DefaultMutableTreeNode node
         = (DefaultMutableTreeNode)value;
      look at node.getUserObject();
      Font font = appropriate font;
      setFont(font);
      return this;
   }
};

CAUTION

graphics/caution.gif
 

The value parameter of the getTreeCellRendererComponent method is the node object, not the user object! Recall that the user object is a feature of the DefaultMutableTreeNode, and that a JTree can contain nodes of an arbitrary type. If your tree uses DefaultMutableTreeNode nodes, then you must retrieve the user object in a second step, as we did in the preceding code sample.

CAUTION

graphics/caution.gif
 

The DefaultTreeCellRenderer uses the same label object for all nodes, only changing the label text for each node. If you change the font for a particular node, you must set it back to its default value when the method is called again. Otherwise, all subsequent nodes will be drawn in the changed font! Look at the code in Example 6-6 to see how to restore the font to the default.

We will not show an example for a tree cell renderer that draws arbitrary graphics. You can look at the list cell renderer at the beginning of this chapter—the technique is entirely analogous.

Let's put tree cell renderers to work. Example 6-6 shows the complete source code for the class tree program. The program displays inheritance hierarchies, and it customizes the display to show abstract classes in italics. You can type the name of any class into the text field at the bottom of the frame. Press the ENTER key or click the "Add" button to add the class and its superclasses to the tree. You must enter the full package name, such as java.util.ArrayList.

This program is a bit tricky because it uses reflection to construct the class tree. This work is contained inside the addClass method. (The details are not that important. We use the class tree in this example because inheritance trees yield a nice supply of trees without laborious coding. If you display trees in your own applications, you will have your own source of hierarchical data.) The method uses the breadth-first search algorithm to find whether the current class is already in the tree by calling the findUserObject method that we implemented in the preceding section. If the class is not already in the tree, we add the superclass to the tree, then make the new class node a child and make that node visible.

The ClassNameTreeCellRenderer sets the class name in either the normal or italic font, depending on the ABSTRACT modifier of the Class object. We don't want to set a particular font since we don't want to change whatever font the look and feel normally uses for labels. For that reason, we use the font from the label and derive an italic font from it. Recall that there is only a single shared JLabel object that is returned by all calls. We need to hang on to the original font and restore it in the next call to the getTreeCellRendererComponent method.

Finally, note how we change the node icons in the ClassTreeFrame constructor.

Example 6-6 ClassTree.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.lang.reflect.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6. import javax.swing.event.*;
  7. import javax.swing.tree.*;
  8.
  9. /**
 10.    This program demonstrates cell rendering by showing
 11.    a tree of classes and their superclasses.
 12. */
 13. public class ClassTree
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new ClassTreeFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame displays the class tree and a text field and
 25.    add button to add more classes into the tree.
 26. *
 27. class ClassTreeFrame extends JFrame
 28. {
 29.    public ClassTreeFrame()
 30.    {
 31.       setTitle("ClassTree");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       // the root of the class tree is Object
 35.       root = new DefaultMutableTreeNode(java.lang.Object.class);
 36.       model = new DefaultTreeModel(root);
 37.       tree = new JTree(model);
 38.
 39.       // add this class to populate the tree with some data
 40.       addClass(getClass());
 41.
 42.       // set up node icons
 43.       ClassNameTreeCellRenderer renderer
 44.          = new ClassNameTreeCellRenderer();
 45.       renderer.setClosedIcon(new ImageIcon("red-ball.gif"));
 46.       renderer.setOpenIcon(new ImageIcon("yellow-ball.gif"));
 47.       renderer.setLeafIcon(new ImageIcon("blue-ball.gif"));
 48.       tree.setCellRenderer(renderer);
 49.
 50.       getContentPane().add(new JScrollPane(tree),
 51.          BorderLayout.CENTER);
 52.
 53.       addTextField();
 54.    }
 55.
 56.    /**
 57.       Add the text field and "Add" button to add a new class.
 58.    */
 59.    public void addTextField()
 60.    {
 61.       JPanel panel = new JPanel();
 62.
 63.       ActionListener addListener = new
 64.          ActionListener()
 65.          {
 66.             public void actionPerformed(ActionEvent event)
 67.             {
 68.                // add the class whose name is in the text field
 69.                try
 70.                {
 71.                   String text = textField.getText();
 72.                   addClass(Class.forName(text));
 73.                   // clear text field to indicate success
 74.                   textField.setText("");
 75.                }
 76.                catch (ClassNotFoundException e)
 77.                {
 78.                   JOptionPane.showMessageDialog(null,
 79.                      "Class not found");
 80.                }
 81.             }
 82.          };
 83.
 84.       // new class names are typed into this text field
 85.       textField = new JTextField(20);
 86.       textField.addActionListener(addListener);
 87.       panel.add(textField);
 88.
 89.       JButton addButton = new JButton("Add");
 90.       addButton.addActionListener(addListener);
 91.       panel.add(addButton);
 92.
 93.       getContentPane().add(panel, BorderLayout.SOUTH);
 94.    }
 95.
 96.    /**
 97.       Finds an object in the tree.
 98.       @param obj the object to find
 99.       @return the node containing the object or null
100.       if the object is not present in the tree
101.    */
102.    public DefaultMutableTreeNode findUserObject(Object obj)
103.    {
104.       // find the node containing a user object
105.       Enumeration e = root.breadthFirstEnumeration();
106.       while (e.hasMoreElements())
107.       {
108.          DefaultMutableTreeNode node
109.             = (DefaultMutableTreeNode)e.nextElement();
110.          if (node.getUserObject().equals(obj))
111.             return node;
112.       }
113.       return null;
114.    }
115.
116.    /**
117.       Adds a new class and any parent classes that aren't
118.       yet part of the tree
119.       @param c the class to add
120.       @return the newly added node.
121.    */
122.    public DefaultMutableTreeNode addClass(Class c)
123.    {
124.       // add a new class to the tree
125.
126.       // skip non-class types
127.       if (c.isInterface() || c.isPrimitive()) return null;
128.
129.       // if the class is already in the tree, return its node
130.       DefaultMutableTreeNode node = findUserObject(c);
131.       if (node != null) return node;
132.
133.       // class isn't present--first add class parent recursively
134.
135.       Class s = c.getSuperclass();
136.
137.       DefaultMutableTreeNode parent;
138.       if (s == null)
139.          parent = root;
140.       else
141.          parent = addClass(s);
142.
143.       // add the class as a child to the parent
144.       DefaultMutableTreeNode newNode
145.          = new DefaultMutableTreeNode(c);
146.       model.insertNodeInto(newNode, parent,
147.          parent.getChildCount());
148.
149.       // make node visible
150.       TreePath path = new TreePath(model.getPathToRoot(newNode));
151.       tree.makeVisible(path);
152.
153.       return newNode;
154.    }
155.
156.    private DefaultMutableTreeNode root;
157.    private DefaultTreeModel model;
158.    private JTree tree;
159.    private JTextField textField;
160.    private static final int WIDTH = 400;
161.    private static final int HEIGHT = 300;
162. }
163.
164. /**
165.    This class renders a class name either in plain or italic.
166.    Abstract classes are italic.
167. */
168. class ClassNameTreeCellRenderer extends DefaultTreeCellRenderer
169. {
170.    public Component getTreeCellRendererComponent(JTree tree,
171.       Object value, boolean selected, boolean expanded,
172.       boolean leaf, int row, boolean hasFocus)
173.    {
174.       super.getTreeCellRendererComponent(tree, value,
175.          selected, expanded, leaf, row, hasFocus);
176.       // get the user object
177.       DefaultMutableTreeNode node
178.          = (DefaultMutableTreeNode)value;
179.       Class c = (Class)node.getUserObject();
180.
181.       // the first time, derive italic font from plain font
182.       if (plainFont == null)
183.       {
184.          plainFont = getFont();
185.          /*
186.             the tree cell renderer is sometimes called with a
187.             label that has a null font
188.          */
189.          if (plainFont != null)
190.             italicFont = plainFont.deriveFont(Font.ITALIC);
191.       }
192.
193.       // set font to italic if the class is abstract
194.       if ((c.getModifiers() & Modifier.ABSTRACT) == 0)
195.          setFont(plainFont);
196.       else
197.          setFont(italicFont);
198.       return this;
199.    }
200.
201.    private Font plainFont = null;
202.    private Font italicFont = null;
203. }
javax.swing.tree.DefaultMutableTreeNode

graphics/api.gif
 

javax.swing.tree.TreeCellRenderer

graphics/api.gif
 

javax.swing.tree.DefaultTreeCellRenderer

graphics/api.gif
 

Listening to Tree Events

Most commonly, a tree component is paired with some other component. When the user selects tree nodes, some information shows up in another window. Look at Figure 6-23 for an example. When the user selects a class, the instance and static variables of that class are displayed in the text area to the right.

Figure 6-23. A class browser

graphics/06fig23.gif

To obtain this behavior, you install a tree selection listener. The listener must implement the TreeSelectionListener interface, an interface with a single method

void valueChanged(TreeSelectionEvent event)

That method is called whenever the user selects or deselects tree nodes.

You add the listener to the tree in the normal way:

tree.addTreeSelectionListener(listener);

You can specify whether the user is allowed to select a single node, a contiguous range of nodes, or an arbitrary, potentially discontiguous, set of nodes. The JTree class uses a TreeSelectionModel to manage node selection. You need to retrieve the model to set the selection state to one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION, or DISCONTIGUOUS_TREE_SELECTION. (Discontiguous selection mode is the default.) For example, in our class browser, we only want to allow selection of a single class:

int mode = TreeSelectionModel.SINGLE_TREE_SELECTION;
tree.getSelectionModel().setSelectionMode(mode);

Apart from setting the selection mode, you need not worry about the tree selection model.

NOTE

graphics/note.gif
 

How the user selects multiple items depends on the look and feel. In the Metal look and feel, hold down the ctrl key while clicking on an item to add the item to the selection, or to remove it if it was currently selected. Hold down the SHIFT key while clicking on an item to select a range of items, extending from the previously selected item to the new item.

To find out the current selection, you query the tree with the getSelectionPaths method:

TreePath[] selectedPaths = tree.getSelectionPaths();

If you restricted the user to a single selection, you can use the convenience method getSelectionPath, which returns the first selected path, or null if no path was selected.

CAUTION

graphics/caution.gif
 

The TreeSelectionEvent class has a getPaths method that returns an array of TreePath objects, but that array describes selection changes, not the current selection.

Example 6-7 puts tree selection to work. This program builds upon Example 6-6; however, to keep the program short, we did not use a custom tree cell renderer. In the frame constructor, we restrict the user to single item selection and add a tree selection listener. When the valueChanged method is called, we ignore its event parameter and simply ask the tree for the current selection path. As always, we need to get the last node of the path and look up its user object. We then call the getFieldDescription method, which uses reflection to assemble a string with all fields of the selected class. Finally, that string is displayed in the text area.

Example 6-7 ClassBrowserTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.lang.reflect.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6. import javax.swing.event.*;
  7. import javax.swing.tree.*;
  8.
  9. /**
 10.    This program demonstrates tree selection events.
 11. */
 12. public class ClassBrowserTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new ClassBrowserTestFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    A frame with a class tree, a text area to show the properties
 24.    of the selected class, and a text field to add new classes.
 25. */
 26. class ClassBrowserTestFrame extends JFrame
 27. {
 28.    public ClassBrowserTestFrame()
 29.    {
 30.       setTitle("ClassBrowserTest");
 31.       setSize(WIDTH, HEIGHT);
 32.
 33.       // the root of the class tree is Object
 34.       root = new DefaultMutableTreeNode(java.lang.Object.class);
 35.       model = new DefaultTreeModel(root);
 36.       tree = new JTree(model);
 37.
 38.       // add this class to populate the tree with some data
 39.       addClass(getClass());
 40.
 41.       // set up selection mode
 42.       tree.addTreeSelectionListener(new
 43.          TreeSelectionListener()
 44.          {
 45.             public void valueChanged(TreeSelectionEvent event)
 46.             {
 47.                // the user selected a different node
 48.                // --update description
 49.                TreePath path = tree.getSelectionPath();
 50.                if (path == null) return;
 51.                DefaultMutableTreeNode selectedNode
 52.                   = (DefaultMutableTreeNode)
 53.                   path.getLastPathComponent();
 54.                Class c = (Class)selectedNode.getUserObject();
 55.                String description = getFieldDescription(c);
 56.                textArea.setText(description);
 57.             }
 58.          });
 59.       int mode = TreeSelectionModel.SINGLE_TREE_SELECTION;
 60.       tree.getSelectionModel().setSelectionMode(mode);
 61.
 62.       // this text area holds the class description
 63.       textArea = new JTextArea();
 64.
 65.       // add tree and text area to the content pane
 66.       JPanel panel = new JPanel();
 67.       panel.setLayout(new GridLayout(1, 2));
 68.       panel.add(new JScrollPane(tree));
 69.       panel.add(new JScrollPane(textArea));
 70.
 71.       getContentPane().add(panel, BorderLayout.CENTER);
 72.
 73.       addTextField();
 74.    }
 75.
 76.    /**
 77.       Add the text field and "Add" button to add a new class.
 78.    */
 79.    public void addTextField()
 80.    {
 81.       JPanel panel = new JPanel();
 82.
 83.       ActionListener addListener = new
 84.          ActionListener()
 85.          {
 86.             public void actionPerformed(ActionEvent event)
 87.             {
 88.                // add the class whose name is in the text field
 89.                try
 90.                {
 91.                   String text = textField.getText();
 92.                   addClass(Class.forName(text));
 93.                   // clear text field to indicate success
 94.                   textField.setText("");
 95.                }
 96.                catch (ClassNotFoundException e)
 97.                {
 98.                   JOptionPane.showMessageDialog(null,
 99.                      "Class not found");
100.                }
101.             }
102.          };
103.
104.       // new class names are typed into this text field
105.       textField = new JTextField(20);
106.       textField.addActionListener(addListener);
107.       panel.add(textField);
108.
109.       JButton addButton = new JButton("Add");
110.       addButton.addActionListener(addListener);
111.       panel.add(addButton);
112.
113.       getContentPane().add(panel, BorderLayout.SOUTH);
114.    }
115.
116.    /**
117.       Finds an object in the tree.
118.       @param obj the object to find
119.       @return the node containing the object or null
120.       if the object is not present in the tree
121.    */
122.    public DefaultMutableTreeNode findUserObject(Object obj)
123.    {
124.       // find the node containing a user object
125.       Enumeration e = root.breadthFirstEnumeration();
126.       while (e.hasMoreElements())
127.       {
128.          DefaultMutableTreeNode node
129.             = (DefaultMutableTreeNode)e.nextElement();
130.          if (node.getUserObject().equals(obj))
131.             return node;
132.       }
133.       return null;
134.    }
135.
136.    /**
137.       Adds a new class and any parent classes that aren't
138.       yet part of the tree
139.       @param c the class to add
140.       @return the newly added node.
141.    */
142.    public DefaultMutableTreeNode addClass(Class c)
143.    {
144.       // add a new class to the tree
145.
146.       // skip non-class types
147.       if (c.isInterface() || c.isPrimitive()) return null;
148.
149.       // if the class is already in the tree, return its node
150.       DefaultMutableTreeNode node = findUserObject(c);
151.       if (node != null) return node;
152.
153.       // class isn't present--first add class parent recursively
154.
155.       Class s = c.getSuperclass();
156.
157.       DefaultMutableTreeNode parent;
158.       if (s == null)
159.          parent = root;
160.       else
161.          parent = addClass(s);
162.
163.       // add the class as a child to the parent
164.       DefaultMutableTreeNode newNode
165.          = new DefaultMutableTreeNode(c);
166.       model.insertNodeInto(newNode, parent,
167.          parent.getChildCount());
168.
169.       // make node visible
170.       TreePath path = new TreePath(model.getPathToRoot(newNode));
171.       tree.makeVisible(path);
172.
173.       return newNode;
174.    }
175.
176.    /**
177.       Returns a description of the fields of a class.
178.       @param the class to be described
179.       @return a string containing all field types and names
180.    */
181.    public static String getFieldDescription(Class c)
182.    {
183.       // use reflection to find types and names of fields
184.       StringBuffer r = new StringBuffer();
185.       Field[] fields = c.getDeclaredFields();
186.       for (int i = 0; i < fields.length; i++)
187.       {
188.          Field f = fields[i];
189.          if ((f.getModifiers() & Modifier.STATIC) != 0)
190.             r.append("static ");
191.          r.append(f.getType().getName());
192.          r.append(" ");
193.          r.append(f.getName());
194.          r.append("\n");
195.       }
196.       return r.toString();
197.    }
198.
199.    private DefaultMutableTreeNode root;
200.    private DefaultTreeModel model;
201.    private JTree tree;
202.    private JTextField textField;
203.    private JTextArea textArea;
204.    private static final int WIDTH = 400;
205.    private static final int HEIGHT = 300;
206.}
javax.swing.JTree

graphics/api.gif
 

javax.swing.event.TreeSelectionListener

graphics/api.gif
 

javax.swing.event.TreeSelectionEvent

graphics/api.gif
 

Custom Tree Models

In the final example, we implement a program that inspects the contents of a variable, just like a debugger does (see Figure 6-24).

Figure 6-24. An object inspection tree

graphics/06fig24.gif

Before going further, compile and run the example program! Each node corresponds to an instance variable. If the variable is an object, expand it to see its instance variables. The program inspects the contents of the frame window. If you poke around a few of the instance variables, you should be able to find some familiar classes. You'll also gain some respect for how complex the Swing user interface components are under the hood.

What's remarkable about the program is that the tree does not use the DefaultTreeModel. If you already have data that is hierarchically organized, you may not want to build a duplicate tree and worry about keeping both trees synchronized. That is the situation in our case—the inspected objects are already linked to each other through the object references, so there is no need to replicate the linking structure.

The TreeModel interface has only a handful of methods. The first group of methods enables the JTree to find the tree nodes by first getting the root, then the children. The JTree class only calls these methods when the user actually expands a node.

Object getRoot()
int getChildCount(Object parent)
Object getChild(Object parent, int index)

This example shows why the TreeModel interface, like the JTree class itself, does not need an explicit notion of nodes. The root and its children can be any objects. The TreeModel is responsible for telling the JTree how they are connected.

The next method of the TreeModel interface is the reverse of getChild:

int getIndexOfChild(Object parent, Object child)

Actually, this method can be implemented in terms of the first three—see the code in Example 6-8.

The tree model tells the JTree which nodes should be displayed as leaves:

boolean isLeaf(Object node)

If your code changes the tree model, then the tree needs to be notified so that it can redraw itself. The tree adds itself as a TreeModelListener to the model. Thus, the model must support the usual listener management methods:

void addTreeModelListener(TreeModelListener l)
void removeTreeModelListener(TreeModelListener l)

You can see implementations for these methods in Example 6-8.

When the model modifies the tree contents, it calls one of the four methods of the TreeModelListener interface:

void treeNodesChanged(TreeModelEvent e)
void treeNodesInserted(TreeModelEvent e)
void treeNodesRemoved(TreeModelEvent e)
void treeStructureChanged(TreeModelEvent e)

The TreeModelEvent object describes the location of the change. The details of assembling a tree model event that describes an insertion or removal event are quite technical. You only need to worry about firing these events if your tree can actually have nodes added and removed. In Example 6-8, we show you how to fire one event: replacing the root with a new object.

TIP

graphics/tip.gif
 

The Swing programmers evidently got tired enough of event firing that they provide a convenience class javax.swing.EventListenerList that collects listeners. See Chapter 8 in Volume 1 for more information on this class.

Finally, if the user edits a tree node, your model gets called with the change:

void valueForPathChanged(TreePath path, Object newValue)

If you don't allow editing, this method is never called.

If you don't need to support editing, then it is very easy to construct a tree model. Implement the three methods

Object getRoot()
int getChildCount(Object parent)
Object getChild(Object parent, int index)

These methods describe the structure of the tree. Supply routine implementations of the other five methods, as in Example 6-8. Then, you are ready to display your tree.

Now let's turn to the implementation of the example program. Our tree will contain objects of type Variable.

NOTE

graphics/note.gif
 

Had we used the DefaultTreeModel, our nodes would have been objects of type DefaultMutableTreeNode with user objects of type Variable.

For example, suppose you inspect the variable

Employee joe;

That variable has a type Employee.class, a name "joe", and a value, the value of the object reference joe. We define a class Variable that describes a variable in a program:

Variable v = new Variable(Employee.class, "joe", joe);

If the type of the variable is a primitive type, you must use an object wrapper for the value.

new Variable(double.class, "salary", new Double(salary));

If the type of the variable is a class, then the variable has fields. Using reflection, we enumerate all fields and collect them in an ArrayList. Since the getFields method of the Class class does not return fields of the superclass, we need to call getFields on all superclasses as well. You will find the code in the Variable constructor. The getFields method of our Variable class returns the array of fields. Finally, the toString method of the Variable class formats the node label. The label always contains the variable type and name. If the variable is not a class, the label also contains the value.

NOTE

graphics/note.gif
 

If the type is an array, then we do not display the elements of the array. This would not be difficult to do; we leave it as the proverbial "exercise for the reader."

Let's move on to the tree model. The first two methods are very simple.

public Object getRoot()
{
   return root;
}

public int getChildCount(Object parent)
{
   return ((Variable)parent).getFields().size();
}

The getChild method returns a new Variable object that describes a particular field. The getType and getName method of the Field class yield the field type and name. By using reflection, you can read the field value as f.get(parentValue). That method can throw an IllegalAccessException. However, we made all fields accessible in the Variable constructor, so this won't happen in practice.

Here is the complete code of the getChild method.

public Object getChild(Object parent, int index)
{
   ArrayList fields = ((Variable)parent).getFields();
   Field f = (Field)fields.get(index);
   Object parentValue = ((Variable)parent).getValue();
   try
   {
      return new Variable(f.getType(), f.getName(),
         f.get(parentValue));
   }
   catch(IllegalAccessException e)
   {
      return null;
   }
}

These three methods reveal the structure of the object tree to the JTree component. The remaining methods are routine—see the source code in Example 6-8.

There is one remarkable fact about this tree model: it actually describes an infinite tree. You can verify this by following one of the WeakReference objects. Click on the variable named referent. It leads you right back to the original object. You get an identical subtree, and you can open its WeakReference object again, ad infinitum. Of course, you cannot store an infinite set of nodes. The tree model simply generates the nodes on demand, as the user expands the parents.

This example concludes our discussion on trees. We move on to the table component, another complex Swing component. Superficially, trees and tables don't seem to have much in common, but you will find that they both use the same concepts for data models and cell rendering.

Example 6-8 ObjectInspectorTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.lang.reflect.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6. import javax.swing.event.*;
  7. import javax.swing.tree.*;
  8.
  9. /**
 10.    This program demonstrates how to use a custom tree
 11.    model. It displays the fields of an object.
 12. */
 13. public class ObjectInspectorTest
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new ObjectInspectorFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame holds the object tree.
 25. */
 26. class ObjectInspectorFrame extends JFrame
 27. {
 28.    public ObjectInspectorFrame()
 29.    {
 30.       setTitle("ObjectInspectorTest");
 31.       setSize(WIDTH, HEIGHT);
 32.
 33.       // we inspect this frame object
 34.
 35.       Variable v = new Variable(getClass(), "this", this);
 36.       ObjectTreeModel model = new ObjectTreeModel();
 37.       model.setRoot(v);
 38.
 39.       // construct and show tree
 40.
 41.       tree = new JTree(model);
 42.       getContentPane().add(new JScrollPane(tree),
 43.          BorderLayout.CENTER);
 44.    }
 45.
 46.    private JTree tree;
 47.    private static final int WIDTH = 400;
 48.    private static final int HEIGHT = 300;
 49. }
 50.
 51. /**
 52.    This tree model describes the tree structure of a Java
 53.    object. Children are the objects that are stored in instance
 54.    variables.
 55. */
 56. class ObjectTreeModel implements TreeModel
 57. {
 58.    /**
 59.       Constructs an empty tree.
 60.    */
 61.    public ObjectTreeModel()
 62.    {
 63.       root = null;
 64.    }
 65.
 66.    /**
 67.       Sets the root to a given variable.
 68.       @param v the variable that is being described by this tree
 69.    */
 70.    public void setRoot(Variable v)
 71.    {
 72.       Variable oldRoot = v;
 73.       root = v;
 74.       fireTreeStructureChanged(oldRoot);
 75.    }
 76.
 77.    public Object getRoot()
 78.    {
 79.       return root;
 80.    }
 81.
 82.    public int getChildCount(Object parent)
 83.    {
 84.       return ((Variable)parent).getFields().size();
 85.    }
 86.
 87.    public Object getChild(Object parent, int index)
 88.    {
 89.       ArrayList fields = ((Variable)parent).getFields();
 90.       Field f = (Field)fields.get(index);
 91.       Object parentValue = ((Variable)parent).getValue();
 92.       try
 93.       {
 94.          return new Variable(f.getType(), f.getName(),
 95.             f.get(parentValue));
 96.       }
 97.       catch(IllegalAccessException e)
 98.       {
 99.          return null;
100.       }
101.    }
102.
103.    public int getIndexOfChild(Object parent, Object child)
104.    {
105.       int n = getChildCount(parent);
106.       for (int i = 0; i < n; i++)
107.          if (getChild(parent, i).equals(child))
108.             return i;
109.       return -1;
110.    }
111.
112.    public boolean isLeaf(Object node)
113.    {
114.       return getChildCount(node) == 0;
115.    }
116.
117.    public void valueForPathChanged(TreePath path,
118.       Object newValue)
119.    {}
120.
121.    public void addTreeModelListener(TreeModelListener l)
122.    {
123.       listenerList.add(TreeModelListener.class, l);
124.    }
125.
126.    public void removeTreeModelListener(TreeModelListener l)
127.    {
128.       listenerList.remove(TreeModelListener.class, l);
129.    }
130.
131.    protected void fireTreeStructureChanged(Object oldRoot)
132.    {
133.       TreeModelEvent event
134.          = new TreeModelEvent(this, new Object[] {oldRoot});
135.       EventListener[] listeners = listenerList.getListeners(
136.          TreeModelListener.class);
137.       for (int i = 0; i < listeners.length; i++)
138.          ((TreeModelListener)listeners[i]).treeStructureChanged(
139.             event);
140.    }
141.
142.    private Variable root;
143.    private EventListenerList listenerList
144.       = new EventListenerList();
145. }
146.
147. /**
148.    A variable with a type, name, and value.
149. */
150. class Variable
151. {
152.    /**
153.       Construct a variable
154.       @param aType the type
155.       @param aName the name
156.       @param aValue the value
157.    */
158.    public Variable(Class aType, String aName, Object aValue)
159.    {
160.       type = aType;
161.       name = aName;
162.       value = aValue;
163.       fields = new ArrayList();
164.
165.       /*
166.          find all fields if we have a class type
167.          except we don't expand strings and null values
168.       */
169.
170.       if (!type.isPrimitive() && !type.isArray() &&
171.          !type.equals(String.class) && value != null)
172.       {
173.          // get fields from the class and all superclasses
174.          for (Class c = value.getClass(); c != null;
175.             c = c.getSuperclass())
176.          {
177.             Field[] f = c.getDeclaredFields();
178.             AccessibleObject.setAccessible(f, true);
179.
180.             // get all nonstatic fields
181.             for (int i = 0; i < f.length; i++)
182.                if ((f[i].getModifiers() & Modifier.STATIC) == 0)
183.                   fields.add(f[i]);
184.          }
185.       }
186.    }
187.
188.    /**
189.       Gets the value of this variable.
190.       @return the value
191.    */
192.    public Object getValue()
193.    {
194.       return value;
195.    }
196.
197.    /**
198.       Gets all nonstatic fields of this variable.
199.       @return an array list of variables describing the fields
200.    */
201.    public ArrayList getFields()
202.    {
203.       return fields;
204.    }
205.
206.    public String toString()
207.    {
208.       String r = type + " " + name;
209.       if (type.isPrimitive())
210.          r += "=" + value;
211.       else if (type.equals(String.class))
212.          r += "=" + value;
213.       else if (value == null)
214.          r += "=null";
215.       return r;
216.    }
217.
218.    private Class type;
219.    private String name;
220.    private Object value;
221.    private ArrayList fields;
222. }
javax.swing.tree.TreeModel

graphics/api.gif
 

javax.swing.event.TreeModelListener

graphics/api.gif
 

javax.swing.event.TreeModelEvent

graphics/api.gif
 

Tables

The JTable component displays a two-dimensional grid of objects. Of course, tables are very common in user interfaces. The Swing team has put a lot of effort into the table control. Tables are inherently complex, but—perhaps more successfully than with other Swing classes—the JTable component hides much of that complexity. You can produce fully functional tables with rich behavior by writing a few lines of code. Of course, you can write more code and customize the display and behavior for your specific applications.

In this section, we explain how to make simple tables, how the user interacts with them, and how to make some of the most common adjustments. As with the other complex Swing controls, it is impossible to cover all aspects in complete detail. If you need more information, you can find it in Core Java Foundation Classes by Kim Topley or Graphic Java 2 by David Geary.

A Simple Table

As with the tree control, a JTable does not store its own data, but obtains its data from a table model. The JTable class has a constructor that wraps a two-dimensional array of objects into a default model. That is the strategy that we will use in our first example. Later in this chapter, we will turn to table models.

Figure 6-25 shows a typical table, describing properties of the planets of the solar system. (A planet is gaseous if it consists mostly of hydrogen and helium. You should take the "Color" entries with a grain of salt—that column was added because it will be useful in a later code example.)

Figure 6-25. A simple table

graphics/06fig25.gif

As you can see from the code in Example 6-9, the data of the table is stored as a two-dimensional array of Object values:

Object[][] cells =
{
   {
      "Mercury", new Double(2440),  new Integer(0),
      Boolean.FALSE, Color.yellow
   },
   {
      "Venus", new Double(6052), new Integer(0),
      Boolean.FALSE, Color.yellow
   },
   . . .
}

The table simply invokes the toString method on each object to display it. That's why the colors show up as java.awt.Color[r=...,g=...,b=...].

You supply the column names in a separate array of strings:

String[] columnNames =
   {
      "Planet", "Radius", "Moons", "Gaseous", "Color"
   };

Then, you construct a table from the cell and column name arrays. Finally, add scroll bars in the usual way, by wrapping the table in a JScrollPane.

JTable table = new JTable(cells, columnNames);
JScrollPane pane = new JScrollPane(table);

The resulting table already has surprisingly rich behavior. Resize the table vertically until the scroll bar shows up. Then, scroll the table. Note that the column headers don't scroll out of view!

Next, click on one of the column headers and drag it to the left or right. See how the entire column becomes detached (see Figure 6-26). You can drop it to a different location. This rearranges the columns in the view only. The data model is not affected.

Figure 6-26. Moving a column

graphics/06fig26.gif

To resize columns, simply place the cursor between two columns until the cursor shape changes to an arrow. Then, drag the column boundary to the desired place (see Figure 6-27).

Figure 6-27. Resizing columns

graphics/06fig27.gif

Users can select rows by clicking anywhere in a row. The selected rows are highlighted; you will see later how to get selection events. Users can also edit the table entries by clicking on a cell and typing into it. However, in this code example, the edits do not change the underlying data. In your programs, you should either make cells uneditable or handle cell editing events and update your model. We will discuss those topics later in this section.

Example 6-9 PlanetTable.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import javax.swing.*;
 4. import javax.swing.table.*;
 5.
 6. /**
 7.    This program demonstrates how to show a simple table
 8. */
 9. public class PlanetTable
10. {
11.    public static void main(String[] args)
12.    {
13.       JFrame frame = new PlanetTableFrame();
14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.       frame.show();
16.    }
17. }
18.
19. /**
20.    This frame contains a table of planet data.
21. */
22. class PlanetTableFrame extends JFrame
23. {
24.    public PlanetTableFrame()
25.    {
26.       setTitle("PlanetTable");
27.       setSize(WIDTH, HEIGHT);
28.
29.       JTable table = new JTable(cells, columnNames);
30.
31.       getContentPane().add(new JScrollPane(table),
32.          BorderLayout.CENTER);
33.    }
34.
35.    private Object[][] cells =
36.    {
37.       {
38.          "Mercury", new Double(2440),  new Integer(0),
39.          Boolean.FALSE, Color.yellow
40.       },
41.       {
42.          "Venus", new Double(6052), new Integer(0),
43.          Boolean.FALSE, Color.yellow
44.       },
45.       {
46.          "Earth", new Double(6378), new Integer(1),
47.          Boolean.FALSE, Color.blue
48.       },
49.       {
50.          "Mars", new Double(3397), new Integer(2),
51.          Boolean.FALSE, Color.red
52.       },
53.       {
54.          "Jupiter", new Double(71492), new Integer(16),
55.          Boolean.TRUE, Color.orange
56.       },
57.       {
58.          "Saturn", new Double(60268), new Integer(18),
59.          Boolean.TRUE, Color.orange
60.       },
61.       {
62.          "Uranus", new Double(25559), new Integer(17),
63.          Boolean.TRUE, Color.blue
64.       },
65.       {
66.          "Neptune", new Double(24766), new Integer(8),
67.          Boolean.TRUE, Color.blue
68.       },
69.       {
70.          "Pluto", new Double(1137), new Integer(1),
71.          Boolean.FALSE, Color.black
72.       }
73.    };
74.
75.    private String[] columnNames =
76.    {
77.       "Planet", "Radius", "Moons", "Gaseous", "Color"
78.    };
79.
80.    private static final int WIDTH = 400;
81.    private static final int HEIGHT = 200;
82.}
javax.swing.JTable

graphics/api.gif
 

Table Models

In the preceding example, the table-rendered objects were stored in a two-dimensional array. However, you should generally not use that strategy in your own code. If you find yourself dumping data into an array to display it as a table, you should instead think about implementing your own table model.

Table models are particularly simple to implement because you can take advantage of the AbstractTableModel class that implements most of the required methods. You only need to supply three methods:

public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);

There are many ways for implementing the getValueAt method. You can simply compute the answer. Or you can look up the value from a database or from some other repository. Let us look at a couple of examples.

In the first example, we construct a table that simply shows some computed values, namely, the growth of an investment under different interest rate scenarios (see Figure 6-28).

Figure 6-28. Growth of an investment

graphics/06fig28.gif

The getValueAt method computes the appropriate value and formats it:

public Object getValueAt(int r, int c)
{
   double rate = (c + minRate) / 100.0;
   int nperiods = r;

   double futureBalance = INITIAL_BALANCE
      * Math.pow(1 + rate, nperiods);

  return
     NumberFormat.getCurrencyInstance().format(futureBalance);
}

The getRowCount and getColumnCount methods simply return the number of rows and columns.

public int getRowCount()
{
   return years;
}

public int getColumnCount()
{
   return maxRate - minRate + 1;
}

If you don't supply column names, the getColumnName method of the AbstractTableModel names the columns A, B, C, and so on. To change column names, override the getColumnName method. You will usually want to override that default behavior. In this example, we simply label each column with the interest rate.

public String getColumnName(int c)
{
   double rate = (c + minRate) / 100.0;
   return
      NumberFormat.getPercentInstance().format(rate);
}

You can find the complete source code in Example 6-10.

Example 6-10 InvestmentTable.java
 1.import java.awt.*;
 2.import java.awt.event.*;
 3.import java.text.*;
 4.import javax.swing.*;
 5.import javax.swing.table.*;
 6.
 7./**
 8.   This program shows how to build a table from a table model.
 9.*/
10. public class InvestmentTable
11. {
12.    public static void main(String[] args)
13.    {
14.       JFrame frame = new InvestmentTableFrame();
15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16.       frame.show();
17.    }
18. }
19.
20. /**
21.    This frame contains the investment table.
22. */
23. class InvestmentTableFrame extends JFrame
24. {
25.    public InvestmentTableFrame()
26.    {
27.       setTitle("InvestmentTable");
28.       setSize(WIDTH, HEIGHT);
29.
30.       TableModel model = new InvestmentTableModel(30, 5, 10);
31.       JTable table = new JTable(model);
32.       getContentPane().add(new JScrollPane(table), "Center");
33.    }
34.
35.    private static final int WIDTH = 600;
36.    private static final int HEIGHT = 300;
37. }
38.
39. /**
40.    This table model computes the cell entries each time they
41.    are requested. The table contents shows the growth of
42.    an investment for a number of years under different interest
43.    rates.
44. */
45. class InvestmentTableModel extends AbstractTableModel
46. {
47.    /**
48.       Constructs an investment table model.
49.       @param y the number of years
50.       @param r1 the lowest interest rate to tabulate
51.       @param r2 the highest interest rate to tabulate
52.    */
53.    public InvestmentTableModel(int y, int r1, int r2)
54.    {
55.       years = y;
56.       minRate = r1;
57.       maxRate = r2;
58.    }
59.
60.    public int getRowCount()
61.    {
62.       return years;
63.    }
64.
65.    public int getColumnCount()
66.    {
67.       return maxRate - minRate + 1;
68.    }
69.
70.    public Object getValueAt(int r, int c)
71.    {
72.       double rate = (c + minRate) / 100.0;
73.       int nperiods = r;
74.
75.       double futureBalance = INITIAL_BALANCE
76.          * Math.pow(1 + rate, nperiods);
77.
78.       return
79.          NumberFormat.getCurrencyInstance().format(futureBalance);
80.    }
81.
82.    public String getColumnName(int c)
83.    {
84.       double rate = (c + minRate) / 100.0;
85.       return
86.          NumberFormat.getPercentInstance().format(rate);
87.    }
88.
89.    private int years;
90.    private int minRate;
91.    private int maxRate;
92.
93.    private static double INITIAL_BALANCE = 100000.0;
94. }
Displaying database records

Probably the most common information to be displayed in a table is a set of records from a database. If you use a professional development environment, it almost certainly includes convenient JavaBeans for accessing database information. However, if you don't have database beans or if you are simply curious what goes on under the hood, you will find the next example interesting. Figure 6-29 shows the output—the result of a query for all rows in a database table.

Figure 6-29. Displaying a query result in a table

graphics/06fig29.gif

In the example program, we define a ResultSetTableModel that fetches data from the result set of a database query. (See Chapter 4 for more information on Java database access and result sets.)

You can obtain the column count and the column names from the result set metadata object rsmd:

public String getColumnName(int c)
{
   try
   {
      return rsmd.getColumnName(c + 1);
   }
   catch(SQLException e)
   {
      . . .
   }
}

public int getColumnCount()
{
   try
   {
      return rsmd.getColumnCount();
   }
   catch(SQLException e)
   {
      . . .
   }
}

If the database supports scrolling cursors, then it is particularly easy to get a cell value: just move the cursor to the requested row and fetch the column value.

public Object getValueAt(int r, int c)
{
   try
   {
      ResultSet rs = getResultSet();
      rs.absolute(r + 1);
      return rs.getObject(c + 1);
   }
   catch(SQLException e)
   {
      e.printStackTrace();
      return null;
   }
}

It makes a lot of sense to use this data model instead of the DefaultTableModel. If you created an array of values, then you would duplicate the cache that the database driver is already managing.

If the database does not support scrolling cursors or if you are using a JDBC 1 driver, then the query data must be cached manually. The example program contains such a manual cache. We factored out the common behavior in a base class ResultSetTableModel. The subclass ScrollingResultSetTableModel uses a scrolling cursor, and the subclass CachingResultSetTableModel caches the result set.

Example 6-11 ResultSetTable.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.sql.*;
  5. import java.util.*;
  6. import javax.swing.*;
  7. import javax.swing.table.*;
  8.
  9. /**
 10.    This program shows how to display the result of a
 11.    database query in a table.
 12. */
 13. public class ResultSetTable
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new ResultSetFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame contains a combo box to select a database table
 25.    and a table to show the data stored in the table
 26. */
 27. class ResultSetFrame extends JFrame
 28. {
 29.    public ResultSetFrame()
 30.    {
 31.       setTitle("ResultSet");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       /* find all tables in the database and add them to
 35.          a combo box
 36.       */
 37.
 38.       Container contentPane = getContentPane();
 39.       tableNames = new JComboBox();
 40.       tableNames.addActionListener(new
 41.          ActionListener()
 42.          {
 43.             public void actionPerformed(ActionEvent evt)
 44.             {
 45.                try
 46.                {
 47.                   if (scrollPane != null)
 48.                      getContentPane().remove(scrollPane);
 49.                   String tableName
 50.                      = (String)tableNames.getSelectedItem();
 51.                   if (rs != null) rs.close();
 52.                   String query = "SELECT * FROM " + tableName;
 53.                   rs = stat.executeQuery(query);
 54.                   if (scrolling)
 55.                      model
 56.                         = new ScrollingResultSetTableModel(rs);
 57.                   else
 58.                      model = new CachingResultSetTableModel(rs);
 59.
 60.                   JTable table = new JTable(model);
 61.                   scrollPane = new JScrollPane(table);
 62.                   getContentPane().add(scrollPane,
 63.                      BorderLayout.CENTER);
 64.                   pack();
 65.                   doLayout();
 66.                }
 67.                catch(SQLException e)
 68.                {
 69.                   e.printStackTrace();
 70.                }
 71.             }
 72.          });
 73.       JPanel p = new JPanel();
 74.       p.add(tableNames);
 75.       contentPane.add(p, BorderLayout.NORTH);
 76.
 77.       try
 78.       {
 79.          conn = getConnection();
 80.          DatabaseMetaData meta = conn.getMetaData();
 81.          if (meta.supportsResultSetType(
 82.             ResultSet.TYPE_SCROLL_INSENSITIVE))
 83.          {
 84.             scrolling = true;
 85.             stat = conn.createStatement(
 86.                ResultSet.TYPE_SCROLL_INSENSITIVE,
 87.                ResultSet.CONCUR_READ_ONLY);
 88.          }
 89.          else
 90.          {
 91.             stat = conn.createStatement();
 92.             scrolling = false;
 93.          }
 94.          ResultSet tables = meta.getTables(null, null, null,
 95.             new String[] { "TABLE" });
 96.          while (tables.next())
 97.             tableNames.addItem(tables.getString(3));
 98.          tables.close();
 99.       }
100.       catch(IOException e)
101.       {
102.          e.printStackTrace();
103.       }
104.       catch(SQLException e)
105.       {
106.          e.printStackTrace();
107.       }
108.
109.       addWindowListener(new
110.          WindowAdapter()
111.          {
112.             public void windowClosing(WindowEvent event)
113.             {
114.                try
115.                {
116.                   conn.close();
117.                }
118.                catch (SQLException e)
119.                {
120.                   e.printStackTrace();
121.                }
122.             }
123.          });
124.    }
125.
126.    /**
127.       Gets a connection from the properties specified in
128.       the file database.properties.
129.       @return the database connection
130.     */
131.    public static Connection getConnection()
132.       throws SQLException, IOException
133.    {
134.       Properties props = new Properties();
135.       FileInputStream in
136.          = new FileInputStream("database.properties");
137.       props.load(in);
138.       in.close();
139.
140.       String drivers = props.getProperty("jdbc.drivers");
141.       if (drivers != null)
142.          System.setProperty("jdbc.drivers", drivers);
143.       String url = props.getProperty("jdbc.url");
144.       String username = props.getProperty("jdbc.username");
145.       String password = props.getProperty("jdbc.password");
146.
147.       return
148.          DriverManager.getConnection(url, username, password);
149.    }
150.
151.    private JScrollPane scrollPane;
152.    private ResultSetTableModel model;
153.    private JComboBox tableNames;
154.    private ResultSet rs;
155.    private Connection conn;
156.    private Statement stat;
157.    private boolean scrolling;
158.
159.    private static final int WIDTH = 400;
160.    private static final int HEIGHT = 300;
161. }
162.
163. /**
164.    This class is the superclass for the scrolling and the
165.    caching result set table model. It stores the result set
166.    and its metadata.
167. */
168. abstract class ResultSetTableModel extends AbstractTableModel
169. {
170.    /**
171.       Constructs the table model.
172.       @param aResultSet the result set to display.
173.    */
174.    public ResultSetTableModel(ResultSet aResultSet)
175.    {
176.       rs = aResultSet;
177.       try
178.       {
179.          rsmd = rs.getMetaData();
180.       }
181.       catch(SQLException e)
182.       {
183.          e.printStackTrace();
184.       }
185.    }
186.
187.    public String getColumnName(int c)
188.    {
189.       try
190.       {
191.          return rsmd.getColumnName(c + 1);
192.       }
193.       catch(SQLException e)
194.       {
195.          e.printStackTrace();
196.          return "";
197.       }
198.    }
199.
200.    public int getColumnCount()
201.    {
202.       try
203.       {
204.          return rsmd.getColumnCount();
205.       }
206.       catch(SQLException e)
207.       {
208.          e.printStackTrace();
209.          return 0;
210.       }
211.    }
212.
213.    /**
214.       Gets the result set that this model exposes.
215.       @return the result set
216.    */
217.    protected ResultSet getResultSet()
218.    {
219.       return rs;
220.    }
221.
222.    private ResultSet rs;
223.    private ResultSetMetaData rsmd;
224. }
225.
226. /**
227.    This class uses a scrolling cursor, a JDBC 2 feature,
228.    to locate result set elements.
229. */
230. class ScrollingResultSetTableModel extends ResultSetTableModel
231. {
232.    /**
233.       Constructs the table model.
234.       @param aResultSet the result set to display.
235.    */
236.    public ScrollingResultSetTableModel(ResultSet aResultSet)
237.    {
238.       super(aResultSet);
239.    }
240.
241.    public Object getValueAt(int r, int c)
242.    {
243.       try
244.       {
245.          ResultSet rs = getResultSet();
246.          rs.absolute(r + 1);
247.          return rs.getObject(c + 1);
248.       }
249.       catch(SQLException e)
250.       {
251.          e.printStackTrace();
252.          return null;
253.       }
254.    }
255.
256.    public int getRowCount()
257.    {
258.       try
259.       {
260.          ResultSet rs = getResultSet();
261.          rs.last();
262.          return rs.getRow();
263.       }
264.       catch(SQLException e)
265.       {
266.          e.printStackTrace();
267.          return 0;
268.       }
269.    }
270. }
271.
272. /*
273.    This class caches the result set data; it can be used
274.    if scrolling cursors are not supported
275. */
276. class CachingResultSetTableModel extends ResultSetTableModel
277. {
278.    public CachingResultSetTableModel(ResultSet aResultSet)
279.    {
280.       super(aResultSet);
281.       try
282.       {
283.          cache = new ArrayList();
284.          int cols = getColumnCount();
285.          ResultSet rs = getResultSet();
286.
287.          /* place all data in an array list of Object[] arrays
288.             We don't use an Object[][] because we don't know
289.             how many rows are in the result set
290.          */
291.
292.          while (rs.next())
293.          {
294.             Object[] row = new Object[cols];
295.             for (int j = 0; j < row.length; j++)
296.                row[j] = rs.getObject(j + 1);
297.             cache.add(row);
298.          }
299.       }
300.       catch(SQLException e)
301.       {
302.          System.out.println("Error " + e);
303.       }
304.    }
305.
306.    public Object getValueAt(int r, int c)
307.    {
308.       if (r < cache.size())
309.          return ((Object[])cache.get(r))[c];
310.       else
311.          return null;
312.    }
313.
314.    public int getRowCount()
315.    {
316.       return cache.size();
317.    }
318.
319.    private ArrayList cache;
320. }

A Sort Filter

The last two examples drove home the point that tables don't store the cell data; they get them from a model. The model need not store the data either. It can compute the cell values or fetch them from somewhere else.

In this section, we introduce another useful technique, a filter model that presents information from another table in a different form. In our example, we will sort the rows in a table. Run the program in Example 6-12 and double-click on one of the column headers. You will see how the rows are rearranged so that the column entries are sorted (See Figure 6-30).

Figure 6-30. Sorting the rows of a table

graphics/06fig30.gif

However, we won't physically rearrange the rows in the data model. Instead, we will use a filter model that keeps an array with the permuted row indexes.

The filter model stores a reference to the actual table model. When the JTable needs to look up a value, the filter model computes the actual row index and gets the value from the model. For example,

public Object getValueAt(int r, int c)
{
   return model.getValueAt(actual row index, c);
}

All other methods are simply passed on to the original model.

public String getColumnName(int c)
{
   return model.getColumnName(c);
}

Figure 6-31 shows how the filter sits between the JTable object and the actual table model.

Figure 6-31. A table model filter

graphics/06fig31.gif

There are two complexities when you implement such a sort filter. First, you need to be notified when the user double-clicks on one of the column headers. We don't want to go into too much detail on this technical point. You can find the code in the addMouseListener method of the SortFilterModel in Example 6-12. Here is the idea behind the code. First, get the table header component and attach a mouse listener. When a double click is detected, you need to find out in which table column the mouse click fell. Then, you need to translate the table column to the model column—they can be different if the user moved the table columns around. Once you know the model column, you can start sorting the table rows.

There is a problem with sorting the table rows. We don't want to physically rearrange the rows. What we want is a sequence of row indexes that tell us how we would rearrange them if they were being sorted. However, the sort algorithms in the Arrays and Collections classes don't tell us how they rearrange the elements. Of course, you could reimplement a sorting algorithm and keep track of the object rearrangements. But there is a much smarter way. The trick is to come up with custom objects and a custom comparison method so that the library sorting algorithm can be pressed into service.

We will sort objects of a type Row. A Row object contains the index r of a row in the model. Compare two such objects as follows: find the elements in the model and compare them. In other words, the compareTo method for Row objects computes

model.getValueAt(r1, c).compareTo(model.getValueAt(r2, c))

Here r1 and r2 are the row indexes of the Row objects, and c is the column whose elements should be sorted.

If the entries of a particular column aren't comparable, we simply compare their string representations. That way, the columns with Boolean and Color values can still be sorted. (Neither of those two classes implement the Comparable interface.)

We make the Row class into an inner class of the SortFilterModel because the compareTo method needs to access the current model and column. Here is the code:

class SortFilterModel extends AbstractTableModel
{  . . .
   private class Row implements Comparable
   {
      public int index;
      public int compareTo(Object other)
      {
         Row otherRow = (Row)other;
         Object a = model.getValueAt(index, sortColumn);
         Object b = model.getValueAt(otherRow.index, sortColumn);
         if (a instanceof Comparable)
            return ((Comparable)a).compareTo(b);
         else
            return a.toString().compareTo(b.toString());
      }
   }

   private TableModel model;
   private int sortColumn;
   private Row[] rows;
}

In the constructor, we build an array rows, initialized such that rows[i] is set to i:

public SortFilterModel(TableModel m)
{
   model = m;
   rows = new Row[model.getRowCount()];
   for (int i = 0; i < rows.length; i++)
   {
      rows[i] = new Row();
      rows[i].index = i;
   }
}

In the sort method, we invoke the Arrays.sort algorithm. It sorts the Row objects. Because the comparison criterion looks at the model elements in the appropriate column, the elements are arranged so that afterwards row[0] contains the index of the smallest element in the column, row[1] contains the index of the next-smallest element, and so on.

When the array is sorted, we notify all table model listeners (in particular, the JTable) that the table contents have changed and must be redrawn.

public void sort(int c)
{
   sortColumn = c;
   Arrays.sort(rows);
   fireTableDataChanged();
}

Finally, we can show you the exact computation of the getValueAt method of the filter class. It simply translates a row index r to the model row index rows[r].index:

public Object getValueAt(int r, int c)
{
   return model.getValueAt(rows[r].index, c);
}

The sort model filter shows again the power of the model-view pattern. Because the data and the display are separated, we are able to change the mapping between the two.

Example 6-12 TableSortTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6. import javax.swing.table.*;
  7.
  8. /**
  9.    This program demonstrates how to sort a table column.
 10.    Double-click on a table column to sort it.
 11. */
 12. public class TableSortTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new TableSortFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame contains a table of planet data.
 24. */
 25. class TableSortFrame extends JFrame
 26. {
 27.    public TableSortFrame()
 28.    {
 29.       setTitle("TableSortTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       // set up table model and interpose sorter
 33.
 34.       DefaultTableModel model
 35.          = new DefaultTableModel(cells, columnNames);
 36.       final SortFilterModel sorter = new SortFilterModel(model);
 37.
 38.       // show table
 39.
 40.       final JTable table = new JTable(sorter);
 41.       getContentPane().add(new JScrollPane(table),
 42.          BorderLayout.CENTER);
 43.
 44.       // set up double click handler for column headers
 45.
 46.       table.getTableHeader().addMouseListener(new
 47.          MouseAdapter()
 48.          {
 49.             public void mouseClicked(MouseEvent event)
 50.             {
 51.                // check for double click
 52.                if (event.getClickCount() < 2) return;
 53.
 54.                // find column of click and
 55.                int tableColumn
 56.                   = table.columnAtPoint(event.getPoint());
 57.
 58.                // translate to table model index and sort
 59.                int modelColumn
 60.                   = table.convertColumnIndexToModel(tableColumn);
 61.                sorter.sort(modelColumn);
 62.             }
 63.          });
 64.    }
 65.
 66.    private Object[][] cells =
 67.    {
 68.       {
 69.          "Mercury", new Double(2440),  new Integer(0),
 70.          Boolean.FALSE, Color.yellow
 71.       },
 72.
 73.       {
 74.          "Venus", new Double(6052), new Integer(0),
 75.          Boolean.FALSE, Color.yellow
 76.       },
 77.       {
 78.          "Earth", new Double(6378), new Integer(1),
 79.          Boolean.FALSE, Color.blue
 80.       },
 81.       {
 82.          "Mars", new Double(3397), new Integer(2),
 83.          Boolean.FALSE, Color.red
 84.       },
 85.       {
 86.          "Jupiter", new Double(71492), new Integer(16),
 87.          Boolean.TRUE, Color.orange
 88.       },
 89.       {
 90.          "Saturn", new Double(60268), new Integer(18),
 91.          Boolean.TRUE, Color.orange
 92.       },
 93.       {
 94.          "Uranus", new Double(25559), new Integer(17),
 95.          Boolean.TRUE, Color.blue
 96.       },
 97.       {
 98.          "Neptune", new Double(24766), new Integer(8),
 99.          Boolean.TRUE, Color.blue
100.       },
101.       {
102.          "Pluto", new Double(1137), new Integer(1),
103.          Boolean.FALSE, Color.black
104.       }
105.    };
106.
107.    private String[] columnNames =
108.    {
109.       "Planet", "Radius", "Moons", "Gaseous", "Color"
110.    };
111.
112.    private static final int WIDTH = 400;
113.    private static final int HEIGHT = 200;
114. }
115.
116. /**
117.    This table model takes an existing table model and produces
118.    a new model that sorts the rows so that the entries in
119.    a particular column are sorted.
120. */
121. class SortFilterModel extends AbstractTableModel
122. {
123.    /**
124.       Constructs a sort filter model.
125.       @param m the table model to filter
126.    */
127.    public SortFilterModel(TableModel m)
128.    {
129.       model = m;
130.       rows = new Row[model.getRowCount()];
131.       for (int i = 0; i < rows.length; i++)
132.       {
133.          rows[i] = new Row();
134.          rows[i].index = i;
135.       }
136.    }
137.
138.    /**
139.       Sorts the rows.
140.       @param c the column that should become sorted
141.    */
142.    public void sort(int c)
143.    {
144.       sortColumn = c;
145.       Arrays.sort(rows);
146.       fireTableDataChanged();
147.    }
148.
149.    // Compute the moved row for the three methods that access
150.    // model elements
151.
152.    public Object getValueAt(int r, int c)
153.    {
154.       return model.getValueAt(rows[r].index, c);
155.    }
156.
157.    public boolean isCellEditable(int r, int c)
158.    {
159.       return model.isCellEditable(rows[r].index, c);
160.    }
161.
162.    public void setValueAt(Object aValue, int r, int c)
163.    {
164.       model.setValueAt(aValue, rows[r].index, c);
165.    }
166.
167.    // delegate all remaining methods to the model
168.
169.    public int getRowCount()
170.    {
171.       return model.getRowCount();
172.    }
173.
174.    public int getColumnCount()
175.    {
176.       return model.getColumnCount();
177.    }
178.
179.    public String getColumnName(int c)
180.    {
181.       return model.getColumnName(c);
182.    }
183.
184.    public Class getColumnClass(int c)
185.    {
186.       return model.getColumnClass(c);
187.    }
188.
189.    /**
190.       This inner class holds the index of the model row
191.       Rows are compared by looking at the model row entries
192.       in the sort column.
193.    */
194.    private class Row implements Comparable
195.    {
196.       public int index;
197.       public int compareTo(Object other)
198.       {
199.          Row otherRow = (Row)other;
200.          Object a = model.getValueAt(index, sortColumn);
201.         Object b = model.getValueAt(otherRow.index, sortColumn);
202.          if (a instanceof Comparable)
203.             return ((Comparable)a).compareTo(b);
204.          else
205.             return a.toString().compareTo(b.toString());
206.
207.             //            return index - otherRow.index;
208.       }
209.    }
210.
211.    private TableModel model;
212.    private int sortColumn;
213.    private Row[] rows;
214. }
javax.swing.table.TableModel

graphics/api.gif
 

javax.swing.table.AbstractTableModel

graphics/api.gif
 

javax.swing.JTable

graphics/api.gif
 

Cell Rendering and Editing

In the next example, we again display our planet data, but this time, we want to give the table more information about the column types. If you define the method

Class getColumnClass(int columnIndex)

of your table model to return the class that describes the column type, then the JTable class picks an appropriate renderer for the class. Table 6-1 shows the renderers that the JTable class provides by default.

You can see the check boxes and images in Figure 6-32. (Thanks to Jim Evins, http://www.snaught.com/JimsCoolIcons/Planets, for providing the planet images!)

Figure 6-32. A table with cell renderers

graphics/06fig32.gif
 

Table 6-1. Default renderers
Type Rendered as
ImageIcon image
Boolean check box
Object string

For other types, you can supply your own cell renderers. Table cell renderers are similar to the tree cell renderers that you saw earlier. They implement the TableCellRenderer interface, which has a single method

Component getTableCellRendererComponent(JTable table,
   Object value, boolean isSelected, boolean hasFocus,
   int row, int column)

That method is called when the table needs to draw a cell. You return a component whose paint method is then invoked to fill the cell area.

To display a cell of type Color, you can simply return a panel whose background color you set to the color object stored in the cell. The color is passed as the value parameter.

class ColorTableCellRenderer implements TableCellRenderer
{
   public Component getTableCellRendererComponent(JTable table,
      Object value, boolean isSelected, boolean hasFocus,
      int row, int column)
   {
      panel.setBackground((Color)value);
      return panel;
   }

   private JPanel panel = new JPanel();
}

You need to tell the table to use this renderer with all objects of type Color. The setDefaultRenderer method of the JTable class lets you establish this association. You supply a Class object and the renderer:

table.setDefaultRenderer(Color.class,
   new ColorTableCellRenderer());

That renderer is now used for all objects of the given type.

NOTE

graphics/note.gif
 

For a more realistic cell renderer, you would want to give visual clues when the cell is selected and when it has editing focus. To do that, you need the cell dimensions and the color schemes for selection and focus. In the Java look and feel, selection is indicated by a pale blue background.

To get the cell dimensions, call the getCellRect method of the JTable class. For the selection colors, call getSelectionBackground and getSelectionForeground.

TIP

graphics/tip.gif
 

If your renderer simply draws a text string or an icon, you can extend the DefaultTableCellRenderer class. It takes care of selection handling and focus for you.

Cell editing

To enable cell editing, the table model must indicate which cells are editable by defining the isCellEditable method. Most commonly, you will want to make certain columns editable. In the example program, we allow editing in four columns.

 public boolean isCellEditable(int r, int c)
 {
    return c == NAME_COLUMN
       || c == MOON_COLUMN
       || c == GASEOUS_COLUMN
       || c == COLOR_COLUMN;
}

 private static final int NAME_COLUMN = 0;
 private static final int MOON_COLUMN = 2;
 private static final int GASEOUS_COLUMN = 3;
 private static final int COLOR_COLUMN = 4;

NOTE

graphics/note.gif
 

The AbstractTableModel defines the isCellEditable method to always return false. The DefaultTableModel overrides the method to always return true.

If you run the program in Example 6-13, note that you can click on the check boxes in the Gaseous column and turn the check marks on and off. If you click on the Moons column, a combo box appears (see Figure 6-33). You will see in a minute how to install such a combo box as cell editor.

Figure 6-33. A cell editor

graphics/06fig33.gif
 

Finally, click on a cell in the first column. The cell gains focus. You can start typing and the cell contents change.

What you just saw in action are the three variations of the DefaultCellEditor class. A DefaultCellEditor can be constructed with a JTextField, a JCheckBox, or a JComboBox. The JTable class automatically installs a check box editor for Boolean cells and a text field editor for all editable cells that don't supply their own renderer. The text fields let the user edit the strings that result from applying toString to the return value of the getValueAt method of the table model.

When the edit is complete, the cell editor passes the result back to the model by calling its setValueAt method. It is up to you to define the setValueAt method of your model to turn the edited result back into an appropriate value.

CAUTION

graphics/caution.gif
 

It is easy for the default text field editor to turn your cell value into a string, simply by calling getValueAt and applying toString. However, for the reverse conversion, the monkey is on your back. When the editing is finished, the cell editor calls setValueAt with the resulting String object. Your setValueAt method needs to know how to parse that string. For example, if your cell stores integers, you need to call Integer.parseInt.

To get a combo box editor, you set a cell editor manually—the JTable component has no idea what values might be appropriate for a particular type. For the Moons column, we wanted to enable the user to pick any value between 0 and 20. Here is the code for initializing the combo box.

JComboBox moonCombo = new JComboBox();
for (int i = 0; i <= 20; i++)
   moonCombo.addItem(new Integer(i));

To construct a DefaultCellEditor, supply the combo box in the constructor:

TableCellEditor moonEditor = new DefaultCellEditor(moonCombo);

Next, we need to install the editor. Unlike the color cell renderer, this editor does not depend on the object type—we don't necessarily want to use it for all objects of type Integer. Instead, we need to install it into a particular column.

The JTable class stores information about table columns in objects of type TableColumn. A TableColumnModel class manages the columns. (Figure 6-34 shows the relationships among the most important table classes.) If you don't want to insert or remove columns dynamically, you won't use the table column model much. However, to get a particular TableColumn object, you need to get the column model to ask it for the column object:

Figure 6-34. Relationship between Table classes

graphics/06fig34.gif

TableColumnModel columnModel = table.getColumnModel()
TableColumn moonColumn
   = columnModel.getColumn(PlanetTableModel.MOON_COLUMN);

Finally, you can install the cell editor:

moonColumn.setCellEditor(moonEditor);

If your cells are taller than the default, you also want to set the row height.

table.setRowHeight(height);

By default, all rows of the table have the same height. You can set the heights of individual rows with the call

table.setRowHeight(row, height);

The actual row height equals the row height that has been set with these methods, reduced by the row margin. The default row margin is 1, but you can change it with the call

table.setRowMargin(margin);
Custom editors

Run the example program again and click on a color. A color chooser pops up to let you pick a new color for the planet. Select a color and click OK. The cell color is updated (See Figure 6-35).

Figure 6-35. Editing the cell color with a color chooser

graphics/06fig35.gif

The color cell editor is not a standard table cell editor but a custom implementation. To create a custom cell editor, you implement the TableCellEditor interface. That interface is a bit tedious, and as of SDK 1.3, an AbstractCellEditor class is provided to take care of the event handling details.

The getTableCellEditorComponent method of the TableCellEditor interface requests a component to render the cell. It is exactly the same as the getTableCellRenderer method of the TableCellRenderer interface, except that there is no focus parameter. Since the cell is being edited, it is presumed to have focus. The editor component temporarily replaces the renderer when the editing is in progress. In our example, we return a blank panel that is not colored. This is an indication to the user that the cell is currently being edited.

Next, you want to have your editor pop up when the user clicks on the cell.

The JTable class calls your editor with an event (such as a mouse click) to find out if that event is acceptable to initiate the editing process. The AbstractCellEditor class defines the method to accept all events.

public boolean isCellEditable(EventObject anEvent)
{
   return true;
}

However, if you override this method to false, then the table would not go through the trouble of inserting the editor component.

Once the editor component is installed, the shouldSelectCell method is called, presumably with the same event. You should initiate editing in this method, for example, by popping up an external edit dialog.

public boolean shouldSelectCell(EventObject anEvent)
{
   colorDialog.setVisible(true);
   return true;
}

If the table wants to cancel or stop the edit (because the user has clicked on another table cell), it calls the cancelCellEditing or stopCellEditing method. You should then hide the dialog. When your stopCellEditing method is called, the table would like to use the partially edited value. You should return true if the current value is valid. In the color chooser, any value is valid. But if you edit other data, you can ensure that only valid data is retrieved from the editor.

Also, you should call the superclass methods that take care of event firing—otherwise, the editing won't be properly canceled.

public void cancelCellEditing()
{
   colorDialog.setVisible(false);
   super.cancelCellEditing();
}

Finally, you need to supply a method that yields the value that the user supplied in the editing process:

public Object getCellEditorValue()
{
   return colorChooser.getColor();
}

To summarize, your custom editor should do the following:

  1. Extend the AbstractCellEditor class and implement the TableCellEditor interface.

  2. Define the getTableCellEditorComponent method to supply a component. This can either be a dummy component (if you pop up a dialog) or a component for in-place editing such as a combo box or text field.

  3. Define the shouldSelectCell, stopCellEditing and cancelCellEditing methods to handle the start, completion, and cancellation of the editing process. The stopCellEditing and cancelCellEditing should call the superclass methods to ensure that listeners are notified.

  4. Define the getCellEditorValue method to return the value that is the result of the editing process.

Finally, you need to indicate when the user is finished editing by calling the stopCellEditing and cancelCellEditing methods. When constructing the color dialog, we install accept and cancel callbacks that fire these events.

colorDialog = JColorChooser.createDialog(null,
   "Planet Color", false, colorChooser,
   new
      ActionListener() // OK button listener
      {
         public void actionPerformed(ActionEvent event)
         {
            stopCellEditing();
         }
      },
   new
      ActionListener() // Cancel button listener
      {
         public void actionPerformed(ActionEvent event)
         {
            cancelCellEditing();
         }
      });

Also, when the user closes the dialog, editing should be canceled. This is achieved by installing a window listener:

colorDialog.addWindowListener(new
   WindowAdapter()
   {
      public void windowClosing(WindowEvent event)
      {
         cancelCellEditing();
      }
   });

This completes the implementation of the custom editor.

You now know how to make a cell editable and how to install an editor. There is one remaining issue—how to update the model with the value that the user edited. When editing is complete, the JTable class calls the following method of the table model:

void setValueAt(Object value, int r, int c)

You need to override the method to store the new value. The value parameter is the object that was returned by the cell editor. If you implemented the cell editor, then you know the type of the object that you return from the getCellEditorValue method. In the case of the DefaultCellEditor, there are three possibilities for that value. It is a Boolean if the cell editor is a check box, a string if it is a text field. If the value comes from a combo box, then it is the object that the user selected.

If the value object does not have the appropriate type, then you need to convert it. That happens most commonly when a number is edited in a text field. In our example, we populated the combo box with Integer objects so that no conversion is necessary.

Example 6-13 TableCellRenderTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6. import javax.swing.table.*;
  7.
  8. /**
  9.    This program demonstrates cell rendering and editing
 10.    in a table.
 11. */
 12. public class TableCellRenderTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new TableCellRenderFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame contains a table of planet data.
 24. */
 25. class TableCellRenderFrame extends JFrame
 26. {
 27.    public TableCellRenderFrame()
 28.    {
 29.       setTitle("TableCellRenderTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       TableModel model = new PlanetTableModel();
 33.       JTable table = new JTable(model);
 34.
 35.       // set up renderers and editors
 36.
 37.       table.setDefaultRenderer(Color.class,
 38.          new ColorTableCellRenderer());
 39.       table.setDefaultEditor(Color.class,
 40.          new ColorTableCellEditor());
 41.
 42.       JComboBox moonCombo = new JComboBox();
 43.       for (int i = 0; i <= 20; i++)
 44.          moonCombo.addItem(new Integer(i));
 45.       TableColumnModel columnModel = table.getColumnModel();
 46.       TableColumn moonColumn
 47.          = columnModel.getColumn(PlanetTableModel.MOON_COLUMN);
 48.       moonColumn.setCellEditor(new DefaultCellEditor(moonCombo));
 49.
 50.       // show table
 51.
 52.       table.setRowHeight(100);
 53.       getContentPane().add(new JScrollPane(table),
 54.          BorderLayout.CENTER);
 55.    }
 56.
 57.    private static final int WIDTH = 600;
 58.    private static final int HEIGHT = 400;
 59. }
 60.
 61. /**
 62.    The planet table model specifies the values, rendering
 63.    and editing properties for the planet data.
 64. */
 65. class PlanetTableModel extends AbstractTableModel
 66. {
 67.    public String getColumnName(int c)
 68.    {
 69.       return columnNames[c];
 70.    }
 71.
 72.    public Class getColumnClass(int c)
 73.    {
 74.       return cells[0][c].getClass();
 75.    }
 76.
 77.    public int getColumnCount()
 78.    {
 79.       return cells[0].length;
 80.    }
 81.
 82.    public int getRowCount()
 83.    {
 84.       return cells.length;
 85.    }
 86.
 87.    public Object getValueAt(int r, int c)
 88.    {
 89.       return cells[r][c];
 90.    }
 91.
 92.    public void setValueAt(Object obj, int r, int c)
 93.    {
 94.       cells[r][c] = obj;
 95.    }
 96.
 97.    public boolean isCellEditable(int r, int c)
 98.    {
 99.       return c == NAME_COLUMN
100.          || c == MOON_COLUMN
101.          || c == GASEOUS_COLUMN
102.          || c == COLOR_COLUMN;
103.    }
104.
105.    public static final int NAME_COLUMN = 0;
106.    public static final int MOON_COLUMN = 2;
107.    public static final int GASEOUS_COLUMN = 3;
108.    public static final int COLOR_COLUMN = 4;
109.
110.    private Object[][] cells =
111.    {
112.       {
113.          "Mercury", new Double(2440),  new Integer(0),
114.          Boolean.FALSE, Color.yellow,
115.          new ImageIcon("Mercury.gif")
116.       },
117.       {
118.          "Venus", new Double(6052), new Integer(0),
119.          Boolean.FALSE, Color.yellow,
120.          new ImageIcon("Venus.gif")
121.       },
122.       {
123.          "Earth", new Double(6378), new Integer(1),
124.          Boolean.FALSE, Color.blue,
125.          new ImageIcon("Earth.gif")
126.       },
127.       {
128.          "Mars", new Double(3397), new Integer(2),
129.          Boolean.FALSE, Color.red,
130.          new ImageIcon("Mars.gif")
131.       },
132.       {
133.          "Jupiter", new Double(71492), new Integer(16),
134.          Boolean.TRUE, Color.orange,
135.          new ImageIcon("Jupiter.gif")
136.       },
137.       {
138.          "Saturn", new Double(60268), new Integer(18),
139.          Boolean.TRUE, Color.orange,
140.          new ImageIcon("Saturn.gif")
141.       },
142.       {
143.          "Uranus", new Double(25559), new Integer(17),
144.          Boolean.TRUE, Color.blue,
145.          new ImageIcon("Uranus.gif")
146.       },
147.       {
148.          "Neptune", new Double(24766), new Integer(8),
149.          Boolean.TRUE, Color.blue,
150.          new ImageIcon("Neptune.gif")
151.       },
152.       {
153.          "Pluto", new Double(1137), new Integer(1),
154.          Boolean.FALSE, Color.black,
155.          new ImageIcon("Pluto.gif")
156.       }
157.    };
158.
159.    private String[] columnNames =
160.    {
161.       "Planet", "Radius", "Moons", "Gaseous", "Color", "Image"
162.    };
163. }
164.
165. /**
166.    This renderer renders a color value as a panel with the
167.    given color.
168. */
169. class ColorTableCellRenderer implements TableCellRenderer
170. {
171.    public Component getTableCellRendererComponent(JTable table,
172.       Object value, boolean isSelected, boolean hasFocus,
173.       int row, int column)
174.    {
175.       panel.setBackground((Color)value);
176.       return panel;
177.    }
178.
179.    // the following panel is returned for all cells, with
180.    // the background color set to the Color value of the cell
181.
182.    private JPanel panel = new JPanel();
183. }
184.
185. /**
186.    This editor pops up a color dialog to edit a cell value
187. */
188. class ColorTableCellEditor extends AbstractCellEditor
189.    implements TableCellEditor
190. {
191.    ColorTableCellEditor()
192.    {
193.       panel = new JPanel();
194.       // prepare color dialog
195.
196.       colorChooser = new JColorChooser();
197.       colorDialog = JColorChooser.createDialog(null,
198.          "Planet Color", false, colorChooser,
199.          new
200.             ActionListener() // OK button listener
201.             {
202.                public void actionPerformed(ActionEvent event)
203.                {
204.                   stopCellEditing();
205.                }
206.             },
207.          new
208.             ActionListener() // Cancel button listener
209.             {
210.                public void actionPerformed(ActionEvent event)
211.                {
212.                   cancelCellEditing();
213.                }
214.             });
215.       colorDialog.addWindowListener(new
216.          WindowAdapter()
217.          {
218.             public void windowClosing(WindowEvent event)
219.             {
220.                cancelCellEditing();
221.             }
222.          });
223.    }
224.
225.    public Component getTableCellEditorComponent(JTable table,
226.       Object value, boolean isSelected, int row, int column)
227.    {
228.       // this is where we get the current Color value. We
229.       // store it in the dialog in case the user starts editing
230.       colorChooser.setColor((Color)value);
231.       return panel;
232.    }
233.
234.    public boolean shouldSelectCell(EventObject anEvent)
235.    {
236.       // start editing
237.       colorDialog.setVisible(true);
238.
239.       // tell caller it is ok to select this cell
240.       return true;
241.    }
242.
243.    public void cancelCellEditing()
244.    {
245.       // editing is canceled--hide dialog
246.       colorDialog.setVisible(false);
247.       super.cancelCellEditing();
248.    }
249.
250.    public boolean stopCellEditing()
251.    {
252.       // editing is complete--hide dialog
253.       colorDialog.setVisible(false);
254.       super.stopCellEditing();
255.
256.       // tell caller is is ok to use color value
257.       return true;
258.    }
259.
260.    public Object getCellEditorValue()
261.    {
262.       return colorChooser.getColor();
263.    }
264.
265.    private Color color;
266.    private JColorChooser colorChooser;
267.    private JDialog colorDialog;
268.    private JPanel panel;
269. }
javax.swing.JTable

graphics/api.gif
 

javax.swing.table.TableModel

graphics/api.gif
 

javax.swing.table.TableCellRenderer

graphics/api.gif
 

javax.swing.table.TableColumnModel

graphics/api.gif
 

javax.swing.table.TableColumn

graphics/api.gif
 

javax.swing.DefaultCellEditor

graphics/api.gif
 

javax.swing.CellEditor

graphics/api.gif
 

javax.swing.table.TableCellEditor

graphics/api.gif
 

javax.swing.JColorChooser

graphics/api.gif
 

Working with Rows and Columns

In this subsection, you will see how to manipulate the rows and columns in a table. As you read through this material, you should keep in mind that a Swing table is quite asymmetric—there are different operations that you can carry out on rows and columns. The table component was optimized to display rows of information with the same structure, such as the result of a database query, not an arbitrary two-dimensional grid of objects. You will see this asymmetry throughout this subsection.

Resizing columns

The TableColumn class gives you control over the resizing behavior of columns. You can set the preferred, minimum, and maximum width with the methods

void setPreferredWidth(int width)
void setMinWidth(int width)
void setMaxWidth(int width)

This information is used by the table component to lay out the columns.

Use the method

void setResizable(boolean resizable)

to control whether the user is allowed to resize the column.

You can programmatically resize a column with the method

void setWidth(int width)

When a column is resized, the default is to leave the total size of the table unchanged. Of course, the width increase or decrease of the resized column must then be distributed over other columns. The default behavior is to change the size of all columns to the right of the resized column. That's a good default because it allows a user to adjust all columns to a desired width, moving from left to right.

You can set another behavior from Table 6-2 by using the method

void setAutoResizeMode(int mode)

of the JTable class.

Table 6-2. Resize modes
Mode Behavior
AUTO_RESIZE_OFF Don't resize other columns; change the table size
AUTO_RESIZE_NEXT_COLUMN Resize the next column only
AUTO_RESIZE_SUBSEQUENT_COLUMNS Resize all subsequent columns equally; this is the default behavior
AUTO_RESIZE_LAST_COLUMN Resize the last column only
AUTO_RESIZE_ALL_COLUMNS Resize all columns in the table; this is not a good choice because it makes it challenging for the user to adjust multiple columns to a desired size

Selecting Rows, Columns, and Cells

Depending on the selection mode, the user can select rows, columns, or individual cells in the table. By default, row selection is enabled. Clicking inside a cell selects the entire row (see Figure 6-36). Call

Figure 6-36. Selecting a row

graphics/06fig36.gif

table.setRowSelectionAllowed(false)

to disable row selection.

When row selection is enabled, you can control whether the user is allowed to select a single row, a contiguous set of rows, or any set of rows. You need to retrieve the selection model and use its setSelectionMode method:

table.getSelectionModel().setSelectionMode(mode);

Here, mode is one of the three values:

ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION

Column selection is disabled by default. You turn it on with the call

table.setColumnSelectionAllowed(true)

Enabling both row and column selection is equivalent to enabling cell selection. Then the user selects ranges of cells (see Figure 6-37). You can also enable that setting with the call

Figure 6-37. Selecting a range of cells

graphics/06fig37.gif

table.setCellSelectionEnabled(true)

NOTE

graphics/note.gif
 

In early versions of the Swing toolkit, when setting both row and column selections, every mouse click selects a "+" shaped area consisting of both the row and the column containing the cursor.

You can find out which rows and columns are selected by calling the getSelectedRows and getSelectedColumns methods. Both return an int[] array of the indexes of the selected items.

You can run the program in Example 6-14 to watch cell selection in action. Enable row, column, or cell selection in the Selection menu and watch how the selection behavior changes.

Hiding and displaying columns

The removeColumn method of the JTable class removes a column from the table view. The column data is not actually removed from the model—it is just hidden from view. The removeColumn method takes a TableColumn argument. If you have the column number (for example, from a call to getSelectedColumns), you need to ask the table model for the actual table column object:

TableColumnModel columnModel = table.getColumnModel();
TableColumn column = columnModel.getColumn(i);
table.removeColumn(column);

If you remember the column, you can later add it back in:

table.addColumn(column);

This method adds the column to the end. If you want it to appear elsewhere, you have to call the moveColumn method.

You can also add a new column that corresponds to a column index in the table model, by adding a new TableColumn object:

table.addColumn(new TableColumn(modelColumnIndex));

You can have multiple table columns that view the same column of the model.

However, there is no JTable method to actually insert a new column into the model or to remove a column from the model. There are also no JTable methods for hiding or showing rows. If you want to hide rows, you can create a filter model similar to the sort filter that you saw earlier.

Adding and removing rows in the default table model

The DefaultTableModel class is a concrete class that implements the TableModel interface. It stores a two-dimensional grid of objects. If you already have your data in a tabular arrangement, then there is no point in copying all the data into a default table model, but it is handy if you quickly need to make a table from a small data set. The DefaultTableModel class has methods for adding rows and columns, and for removing rows.

The addRow and addColumn methods add a row or column of new data. You supply an Object[] array or a vector that holds the new data. With the addColumn method, you also need to supply a name for the new column. These methods add the new data to the end of the grid. To insert a row in the middle, use the insertRow method. There is no method for inserting a column in the middle of the grid.

Conversely, the removeRow method removes a row from the model. There is no method for removing a column.

Since the JTable object registers itself as a table model listener, the model notifies the table when data is inserted or removed. At that time, the table refreshes the display.

The program in Example 6-14 shows both selection and editing at work. A default table model contains a simple data set (a multiplication table). The Edit menu contains these commands:

This example concludes the discussion of Swing tables. Tables are conceptually a bit easier to grasp than trees because the underlying data model—a grid of objects—is easy to visualize. However, under the hood, the table component is actually quite a bit more complex than the tree component. Column headers, resizable columns, and column-specific renderers and editors all add to the complexity. In this section, we focused on those topics that you are most likely to encounter in practice: displaying database information, sorting, and custom cell rendering and editing. If you have special advanced needs, we once again refer you to Core Java Foundation Classes by Kim Topley and Graphic Java 2 by David Geary.

Example 6-14 TableSelectionTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. import java.text.*;
  5. import javax.swing.*;
  6. import javax.swing.table.*;
  7.
  8. /**
  9.    This program demonstrates selection, addition, and removal
 10.    of rows and columns.
 11. */
 12. public class TableSelectionTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new TableSelectionFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame shows a multiplication table and has menus for
 24.    setting the row/column/cell selection modes, and for
 25.    adding and removing rows and columns.
 26. */
 27. class TableSelectionFrame extends JFrame
 28. {
 29.    public TableSelectionFrame()
 30.    {
 31.       setTitle("TableSelectionTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       // set up multiplication table
 35.
 36.       model = new DefaultTableModel(10, 10);
 37.
 38.       for (int i = 0; i < model.getRowCount(); i++)
 39.          for (int j = 0; j < model.getColumnCount(); j++)
 40.             model.setValueAt(
 41.                new Integer((i + 1) * (j + 1)), i, j);
 42.
 43.       table = new JTable(model);
 44.       Container contentPane = getContentPane();
 45.       contentPane.add(new JScrollPane(table), "Center");
 46.
 47.       removedColumns = new ArrayList();
 48.
 49.       // create menu
 50.
 51.       JMenuBar menuBar = new JMenuBar();
 52.       setJMenuBar(menuBar);
 53.
 54.       JMenu selectionMenu = new JMenu("Selection");
 55.       menuBar.add(selectionMenu);
 56.
 57.       final JCheckBoxMenuItem rowsItem
 58.          = new JCheckBoxMenuItem("Rows");
 59.       final JCheckBoxMenuItem columnsItem
 60.          = new JCheckBoxMenuItem("Columns");
 61.       final JCheckBoxMenuItem cellsItem
 62.          = new JCheckBoxMenuItem("Cells");
 63.
 64.       rowsItem.setSelected(table.getRowSelectionAllowed());
 65.       columnsItem.setSelected(table.getColumnSelectionAllowed());
 66.       cellsItem.setSelected(table.getCellSelectionEnabled());
 67.
 68.       rowsItem.addActionListener(new
 69.          ActionListener()
 70.          {
 71.             public void actionPerformed(ActionEvent event)
 72.             {
 73.                table.clearSelection();
 74.                table.setRowSelectionAllowed(
 75.                   rowsItem.isSelected());
 76.                cellsItem.setSelected(
 77.                   table.getCellSelectionEnabled());
 78.             }
 79.          });
 80.       selectionMenu.add(rowsItem);
 81.
 82.       columnsItem.addActionListener(new
 83.          ActionListener()
 84.          {
 85.             public void actionPerformed(ActionEvent event)
 86.             {
 87.                table.clearSelection();
 88.                table.setColumnSelectionAllowed(
 89.                   columnsItem.isSelected());
 90.                cellsItem.setSelected(
 91.                   table.getCellSelectionEnabled());
 92.             }
 93.          });
 94.       selectionMenu.add(columnsItem);
 95.
 96.       cellsItem.addActionListener(new
 97.          ActionListener()
 98.          {
 99.             public void actionPerformed(ActionEvent event)
100.             {
101.                table.clearSelection();
102.                table.setCellSelectionEnabled(
103.                   cellsItem.isSelected());
104.                rowsItem.setSelected(
105.                   table.getRowSelectionAllowed());
106.                columnsItem.setSelected(
107.                   table.getColumnSelectionAllowed());
108.             }
109.          });
110.       selectionMenu.add(cellsItem);
111.
112.       JMenu tableMenu = new JMenu("Edit");
113.       menuBar.add(tableMenu);
114.
115.       JMenuItem hideColumnsItem = new JMenuItem("Hide Columns");
116.       hideColumnsItem.addActionListener(new
117.          ActionListener()
118.          {
119.             public void actionPerformed(ActionEvent event)
120.             {
121.                int[] selected = table.getSelectedColumns();
122.                TableColumnModel columnModel
123.                   = table.getColumnModel();
124.
125.                // remove columns from view, starting at the last
126.                // index so that column numbers aren't affected
127.
128.
129.                for (int i = selected.length - 1; i >= 0; i--)
130.                {
131.                   TableColumn column
132.                      = columnModel.getColumn(selected[i]);
133.                   table.removeColumn(column);
134.
135.                   // store removed columns for "show columns"
136.                   // command
137.
138.                   removedColumns.add(column);
139.                }
140.             }
141.          });
142.       tableMenu.add(hideColumnsItem);
143.
144.       JMenuItem showColumnsItem = new JMenuItem("Show Columns");
145.       showColumnsItem.addActionListener(new
146.          ActionListener()
147.          {
148.             public void actionPerformed(ActionEvent event)
149.             {
150.                // restore all removed columns
151.                for (int i = 0; i < removedColumns.size(); i++)
152.                   table.addColumn(
153.                      (TableColumn)removedColumns.get(i));
154.                removedColumns.clear();
155.             }
156.          });
157.       tableMenu.add(showColumnsItem);
158.
159.       JMenuItem addRowItem = new JMenuItem("Add Row");
160.       addRowItem.addActionListener(new
161.          ActionListener()
162.          {
163.             public void actionPerformed(ActionEvent event)
164.             {
165.                // add a new row to the multiplication table in
166.                // the model
167.
168.                Integer[] newCells
169.                   = new Integer[model.getColumnCount()];
170.                for (int i = 0; i < newCells.length; i++)
171.                   newCells[i] = new Integer((i + 1)
172.                      * (model.getRowCount() + 1));
173.                model.addRow(newCells);
174.             }
175.          });
176.       tableMenu.add(addRowItem);
177.
178.       JMenuItem removeRowsItem = new  JMenuItem("Remove Rows");
179.       removeRowsItem.addActionListener(new
180.          ActionListener()
181.          {
182.             public void actionPerformed(ActionEvent event)
183.             {
184.                int[] selected = table.getSelectedRows();
185.
186.                // remove rows from model, starting at the last
187.                // index so that the row numbers aren't affected
188.
189.
190.               for (int i = selected.length - 1; i >= 0; i--)
191.                   model.removeRow(selected[i]);
192.             }
193.          });
194.       tableMenu.add(removeRowsItem);
195.
196.       JMenuItem clearCellsItem = new  JMenuItem("Clear Cells");
197.       clearCellsItem.addActionListener(new
198.          ActionListener()
199.          {
200.             public void actionPerformed(ActionEvent event)
201.             {
202.                // set all selected cells to 0
203.
204.                for (int i = 0; i < table.getRowCount(); i++)
205.                 for (int j = 0; j < table.getColumnCount(); j++)
206.                      if (table.isCellSelected(i, j))
207.                         table.setValueAt(new Integer(0), i, j);
208.             }
209.          });
210.       tableMenu.add(clearCellsItem);
211.    }
212.
213.    private DefaultTableModel model;
214.    private JTable table;
215.    private ArrayList removedColumns;
216.
217.    private static final int WIDTH = 400;
218.    private static final int HEIGHT = 300;
219. }
javax.swing.JTable

graphics/api.gif
 

javax.swing.table.TableColumn

graphics/api.gif
 

javax.swing.ListSelectionModel

graphics/api.gif
 

javax.swing.table.DefaultTableModel

graphics/api.gif
 

Styled Text Components

In Volume 1, we discussed the basic text component classes JTextField and JTextArea. Of course, these classes are very useful for obtaining text input from the user. There is another useful class, JEditorPane, that displays and edits text in HTML and RTF format. (RTF is the "rich text format" that is used by a number of Microsoft applications for document interchange. It is a poorly documented format that doesn't work well even between Microsoft's own applications. We do not cover the RTF capabilities in this book; Sun claims only "limited" support for it. We wouldn't be surprised to see this feature dropped in the future since it would make more sense for Sun to spend its resources on improving the HTML support.)

Frankly, at this point, the JEditorPane is pretty limited. The HTML renderer can display simple files, but it chokes at many complex pages that you typically find on the Web. The HTML editor is limited and unstable. Of course, except for HTML editors, few applications require users to edit HTML text, so this is not a major restriction.

We think that the perfect application for the JEditorPane is to display program help in HTML format. Since you have control over the help files that you provide, you can stay away from features that the JEditorPane does not display well.

NOTE

graphics/note.gif
 

For more information on an industrial-strength help system, check out JavaHelp at http://java.sun.com/products/javahelp/index.html.

NOTE

graphics/note.gif
 

The subclass JTextPane of JEditorPane can hold styled text with special fonts and text formats, as well as embedded components. We will not cover that component in this book. If you need to implement a component that allows users of your program to enter styled text, have a look at the implementation of the StylePad demo that is included in the SDK.

The program in Example 6-15 contains an editor pane that shows the contents of an HTML page. Type a URL into the text field. The URL must start with http: or file:. Then, click the Load button. The selected HTML page is displayed in the editor pane (see Figure 6-38 ).

Figure 6-38. The editor pane displaying an HTML page

graphics/06fig38.gif

The hyperlinks are active: if you click on a link, the application loads it. The Back button returns to the previous page.

This program is in fact a very simple browser. Of course, it does not have any of the comfort features, such as page caching or bookmark lists, that you expect from a commercial browser. Also, the editor pane does not yet display applets.

If you click on the Editable check box, then the editor pane becomes editable. You can type in text and use the BACKSPACE key to delete text. The component also understands the CTRL+X, CTRL+C, and CTRL+V shortcuts for cut, copy, and paste.

However, you would have to do quite a bit of programming to add support for fonts and formatting.

When the component is editable, then hyperlinks are not active. Also, with some web pages you can see JavaScript commands, comments, and other tags when edit mode is turned on (see Figure 6-39 ). The example program lets you investigate the editing feature, but we recommend that you omit that feature in your programs.

Figure 6-39. The editor pane in edit mode

graphics/06fig39.gif

TIP

graphics/tip.gif
 

By default, the JEditorPane is in edit mode. You should call editorPane.setEditable(false) to turn it off.

The features of the editor pane that you saw in the example program are very easy to use. You use the setPage method to load a new document. The parameter is either a string or a URL object. The JEditorPane class extends the JTextComponent class. Therefore, you can call the setText method as well—it simply displays plain text.

To listen to hyperlink clicks, you add a HyperlinkListener. The HyperlinkListener interface has a single method, hyperlinkUpdate, that is called when the user moves over or clicks on a link. The method has a parameter of type HyperlinkEvent.

You need to call the getEventType method to find out what kind of event occurred. There are three possible return values:

HyperlinkEvent.EventType.ACTIVATED
HyperlinkEvent.EventType.ENTERED
HyperlinkEvent.EventType.EXITED

The first value indicates that the user clicked on the hyperlink. In that case, you typically want to open the new link. You can use the second and third values to give some visual feedback, such as a tooltip, when the mouse hovers over the link.

NOTE

graphics/note.gif
 

It is a complete mystery why there aren't three separate methods to handle activation, entry, and exit in the HyperlinkListener interface.

The getURL method of the HyperlinkEvent class returns the URL of the hyperlink. For example, here is how you can install a hyperlink listener that follows the links that a user activates:

editorPane.addHyperlinkListener(new
   HyperlinkListener()
   {
      public void hyperlinkUpdate(HyperlinkEvent event)
      {
         if (event.getEventType()
            == HyperlinkEvent.EventType.ACTIVATED)
         {
            try
            {
               editorPane.setPage(event.getURL());
            }
            catch(IOException e)
            {
               editorPane.setText("Exception: " + e);
            }
         }
      }
   });

The event handler simply gets the URL and updates the editor pane. The set Page method can throw an IOException. In that case, we display an error message as plain text.

The program in Example 6-15 shows all the features that you need to put together an HTML help system. Under the hood, the JEditorPane is even more complex than the tree and table components. However, if you don't need to write a text editor or a renderer of a custom text format, that complexity is hidden from you.

Example 6-15 EditorPaneTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6. import javax.swing.event.*;
  7.
  8. /**
  9.    This program demonstrates how to display HTML documents
 10.    in an editor pane.
 11. */
 12. public class EditorPaneTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new EditorPaneFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame contains an editor pane, a text field and button
 24.    to enter a URL and load a document, and a Back button to
 25.    return to a previously loaded document.
 26. */
 27. class EditorPaneFrame extends JFrame
 28. {
 29.    public EditorPaneFrame()
 30.    {
 31.       setTitle("EditorPaneTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       final Stack urlStack = new Stack();
 35.       final JEditorPane editorPane = new JEditorPane();
 36.       final JTextField url = new JTextField(30);
 37.
 38.       // set up hyperlink listener
 39.
 40.       editorPane.setEditable(false);
 41.       editorPane.addHyperlinkListener(new
 42.          HyperlinkListener()
 43.          {
 44.             public void hyperlinkUpdate(HyperlinkEvent event)
 45.             {
 46.                if (event.getEventType()
 47.                   == HyperlinkEvent.EventType.ACTIVATED)
 48.                {
 49.                   try
 50.                   {
 51.                      // remember URL for back button
 52.                      urlStack.push(event.getURL().toString());
 53.                      // show URL in text field
 54.                      url.setText(event.getURL().toString());
 55.
 56.                      editorPane.setPage(event.getURL());
 57.                   }
 58.                   catch(IOException e)
 59.                   {
 60.                      editorPane.setText("Exception: " + e);
 61.                   }
 62.                }
 63.             }
 64.          });
 65.
 66.       // set up checkbox for toggling edit mode
 67.
 68.       final JCheckBox editable = new JCheckBox();
 69.       editable.addActionListener(new
 70.          ActionListener()
 71.          {
 72.             public void actionPerformed(ActionEvent event)
 73.             {
 74.                editorPane.setEditable(editable.isSelected());
 75.             }
 76.          });
 77.
 78.       // set up load button for loading URL
 79.
 80.       ActionListener listener = new
 81.          ActionListener()
 82.          {
 83.             public void actionPerformed(ActionEvent event)
 84.             {
 85.                try
 86.                {
 87.                   // remember URL for back button
 88.                   urlStack.push(url.getText());
 89.
 90.                   editorPane.setPage(url.getText());
 91.                }
 92.                catch(IOException e)
 93.                {
 94.                   editorPane.setText("Exception: " + e);
 95.                }
 96.             }
 97.          };
 98.
 99.       JButton loadButton = new JButton("Load");
100.       loadButton.addActionListener(listener);
101.       url.addActionListener(listener);
102.
103.       // set up back button and button action
104.
105.       JButton backButton = new JButton("Back");
106.       backButton.addActionListener(new
107.          ActionListener()
108.          {
109.             public void actionPerformed(ActionEvent event)
110.             {
111.                if (urlStack.size() <= 1) return;
112.                try
113.                {
114.                   // get URL from back button
115.                   urlStack.pop();
116.                   // show URL in text field
117.                   String urlString = (String)urlStack.peek();
118.                   url.setText(urlString);
119.
120.                   editorPane.setPage(urlString);
121.                }
122.                catch(IOException e)
123.                {
124.                   editorPane.setText("Exception: " + e);
125.                }
126.             }
127.          });
128.
129.       Container contentPane = getContentPane();
130.       contentPane.add(new JScrollPane(editorPane),
131.          BorderLayout.CENTER);
132.
133.       // put all control components in a panel
134.
135.       JPanel panel = new JPanel();
136.       panel.add(new JLabel("URL"));
137.       panel.add(url);
138.       panel.add(loadButton);
139.       panel.add(backButton);
140.       panel.add(new JLabel("Editable"));
141.       panel.add(editable);
142.
143.       contentPane.add(panel, BorderLayout.SOUTH);
144.    }
145.
146.    private static final int WIDTH = 600;
147.    private static final int HEIGHT = 400;
148. }

javax.swing.JEditorPane

graphics/api.gif
 

javax.swing.event.HyperlinkListener

graphics/api.gif
 

javax.swing.HyperlinkEvent

graphics/api.gif
 

Component Organizers

We conclude the discussion of advanced Swing features with a presentation of components that help organize other components. These include the split pane, a mechanism for splitting an area into multiple parts whose boundaries can be adjusted, the tabbed pane, which uses tab dividers to allow a user to flip through multiple panels, and the desktop pane, which can be used to implement applications that display multiple internal frames.

Split Panes

Split panes are used to split a component into two parts, with an adjustable boundary in between. Figure 6-40 shows a frame with two split panes. The outer pane is split horizontally, with a text area on the bottom and another split pane on the top. That pane is split vertically, with a list on the left and a label containing an image on the right.

Figure 6-40. A frame with two nested split panes

graphics/06fig40.gif

You construct a split pane by specifying the orientation, one of JSplitPane.HORIZONTAL_SPLIT or JSplitPane.VERTICAL_SPLIT, followed by the two components. For example,

JSplitPane innerPane
   = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
      planetList, planetImage);

That's all you have to do. If you like, you can add "one touch expand" icons to the splitter bar. You see those icons in the top pane in Figure 6-40 . In the Metal look and feel, they are small triangles. If you click on one of them, the splitter moves all the way in the direction of the tip of the triangle, expanding one of the panes completely.

To add this capability, call

innerPane.setOneTouchExpandable(true);

The "continuous layout" feature continuously repaints the contents of both components as the user adjusts the splitter. That looks classier, but it can be slow. You turn on that feature with the call

innerPane.setContinuousLayout(true);

In the example program, we left the bottom splitter at the default (no continuous layout). When you drag it, you only move a black outline. When you are done, the components are repainted.

The program in Example 6-16 is very straightforward. It populates a list box with planets. When the user makes a selection, the planet image is displayed to the right and a description is placed in the text area on the bottom. When you run the program, adjust the splitters and try out the "one touch expansion" and "continuous layout" features.

Example 6-16 SplitPaneTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6.
  7. /**
  8.    This program demonstrates the split pane component
  9.    organizer.
 10. */
 11. public class SplitPaneTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new SplitPaneFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19. }
 20.
 21. /**
 22.    This frame consists of two nested split panes to demonstrate
 23.    planet images and data.
 24. */
 25. class SplitPaneFrame extends JFrame
 26. {
 27.    public SplitPaneFrame()
 28.     {
 29.       setTitle("SplitPaneTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       // set up components for planet names, images, descriptions
 33.
 34.       final JList planetList = new JList(planets);
 35.       final JLabel planetImage = new JLabel();
 36.       final JTextArea description = new JTextArea();
 37.
 38.       planetList.addListSelectionListener(new
 39.          ListSelectionListener()
 40.          {
 41.             public void valueChanged(ListSelectionEvent event)
 42.             {
 43.                Planet value
 44.                  = (Planet)planetList.getSelectedValue();
 45.
 46.                // update image and description
 47.
 48.                planetImage.setIcon(value.getImage());
 49.                description.setText(value.getDescription());
 50.             }
 51.          });
 52.
 53.       // set up split panes
 54.
 55.       JSplitPane innerPane
 56.          = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
 57.             planetList, planetImage);
 58.
 59.       innerPane.setContinuousLayout(true);
 60.       innerPane.setOneTouchExpandable(true);
 61.
 62.       JSplitPane outerPane
 63.          = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
 64.             innerPane, description);
 65.
 66.       getContentPane().add(outerPane, "Center");
 67.    }
 68.
 69.    private Planet[] planets =
 70.       {
 71.          new Planet("Mercury", 2440, 0),
 72.          new Planet("Venus", 6052, 0),
 73.          new Planet("Earth", 6378, 1),
 74.          new Planet("Mars", 3397, 2),
 75.          new Planet("Jupiter", 71492, 16),
 76.          new Planet("Saturn", 60268, 18),
 77.          new Planet("Uranus", 25559, 17),
 78.          new Planet("Neptune", 24766, 8),
 79.          new Planet("Pluto", 1137, 1),
 80.       };
 81.    private static final int WIDTH = 300;
 82.    private static final int HEIGHT = 200;
 83. }
 84.
 85. /**
 86.    Describes a planet.
 87. */
 88. class Planet
 89. {
 90.    /**
 91.       Constructs a planet.
 92.       @param n the planet name
 93.       @param r the planet radius
 94.       @param m the number of moons
 95.    */
 96.    public Planet(String n, double r, int m)
 97.    {  name = n;
 98.       radius = r;
 99.       moons = m;
100.       image = new ImageIcon(name + ".gif");
101.    }
102.
103.    public String toString()
104.    {
105.       return name;
106.    }
107.
108.    /**
109.       Gets a description of the planet.
110.       @return the description
111.    */
112.    public String getDescription()
113.    {
114.       return "Radius: " + radius + "\nMoons: " + moons + "\n";
115.    }
116.
117.    /**
118.       Gets an image of the planet.
119.       @return the image
120.    */
121.    public ImageIcon getImage()
122.    {
123.       return image;
124.    }
125.
126.    private String name;
127.    private double radius;
128.    private int moons;
129.    private ImageIcon image;
130.}
javax.swing.JSplitPane

graphics/api.gif
 

Tabbed Panes

Tabbed panes are a familiar user interface device to break up a complex dialog in7to subsets of related options. You can also use tabs to let a user flip through a set of documents or images (see Figure 6-41 ). That is what we will do in our sample program.

Figure 6-41. A tabbed pane

graphics/06fig41.gif

To create a tabbed pane, you first construct a JTabbedPane object, then you add tabs to it.

JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(title, icon, component);

The last parameter of the addTab method has type Component. If you want to add multiple components into the same tab, you first pack them up in a container, such as a JPanel.

The icon is optional; there is an addTab method that does not require an icon:

tabbedPane.addTab(title, component);

You can also add a tab in the middle of the tab collection with the insertTab method:

tabbedPane.insertTab(title, icon, component, index);

To remove a tab from the tab collection, use

tabPane.removeTabAt(index);

When you add a new tab to the tab collection, it is not automatically displayed. You must select it with the setSelectedIndex method. For example, here is how you show a tab that you just added to the end:

tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);

If you have a lot of tabs, then they can take up quite a bit of space. Starting with SDK 1.4, you can display the tabs in scrolling mode, where only one row of tabs is displayed, together with a set of arrow buttons that allow the user to scroll through the tab set (see Figure 6-42 ).

Figure 6-42. A tabbed pane with scrolling tabs

graphics/06fig42.gif

You set the tab layout to wrapped or scrolling mode by calling

tabbedPane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);

or

tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

The example program shows a useful technique with tabbed panes. Sometimes, you want to update a component just before it is displayed. In our example program, we will load the planet image only when the user actually clicks on a tab.

To be notified whenever the user clicks on a new tab, you install a ChangeListener with the tabbed pane. Note that you must install the listener with the tabbed pane itself, not with any of the components.

tabbedPane.addChangeListener(listener);

When the user selects a tab, the stateChanged method of the change listener is called. You retrieve the tabbed pane as the source of the event. Call the getSelectedIndex method to find out which pane is about to be selected.

public void stateChanged(ChangeEvent event)
{
   int n = tabbedPane.getSelectedIndex();
   . . .
}

In Example 6-17 , we first set all tab components to null. When a new tab is selected, we test if its component is still null. If so, we replace it with the image. (This happens instantaneously when you click on the tab. You will not see an empty pane.) Just for fun, we also change the icon from a yellow ball to a red ball to indicate which panes have been visited.

Example 6-17 TabbedPaneTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6.
  7. /**
  8.    This program demonstrates the tabbed pane component organizer.
  9. */
 10. public class TabbedPaneTest
 11. {
 12.    public static void main(String[] args)
 13.    {
 14.       JFrame frame = new TabbedPaneFrame();
 15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 16.       frame.show();
 17.    }
 18. }
 19.
 20. /**
 21.    This frame shows a tabbed pane and radio buttons to
 22.    switch between wrapped and scrolling tab layout.
 23. */
 24. class TabbedPaneFrame extends JFrame
 25. {
 26.    public TabbedPaneFrame()
 27.    {
 28.       setTitle("TabbedPaneTest");
 29.       setSize(WIDTH, HEIGHT);
 30.
 31.       final JTabbedPane tabbedPane = new JTabbedPane();
 32.       // we set the components to null and delay their
 33.       // loading until the tab is shown for the first time
 34.
 35.       ImageIcon icon = new ImageIcon("yellow-ball.gif");
 36.
 37.       tabbedPane.addTab("Mercury", icon, null);
 38.       tabbedPane.addTab("Venus", icon, null);
 39.       tabbedPane.addTab("Earth", icon, null);
 40.       tabbedPane.addTab("Mars", icon, null);
 41.       tabbedPane.addTab("Jupiter", icon, null);
 42.       tabbedPane.addTab("Saturn", icon, null);
 43.       tabbedPane.addTab("Uranus", icon, null);
 44.       tabbedPane.addTab("Neptune", icon, null);
 45.       tabbedPane.addTab("Pluto", icon, null);
 46.
 47.       getContentPane().add(tabbedPane, "Center");
 48.
 49.       tabbedPane.addChangeListener(new
 50.          ChangeListener()
 51.          {
 52.             public void stateChanged(ChangeEvent event)
 53.             {
 54.
 55.                // check if this tab still has a null component
 56.
 57.                if (tabbedPane.getSelectedComponent() == null)
 58.                {
 59.                   // set the component to the image icon
 60.
 61.                   int n = tabbedPane.getSelectedIndex();
 62.                   String title = tabbedPane.getTitleAt(n);
 63.                   ImageIcon planetIcon
 64.                      = new ImageIcon(title + ".gif");
 65.                   tabbedPane.setComponentAt(n,
 66.                      new JLabel(planetIcon));
 67.
 68.                   // indicate that this tab has been
 69.                   // visited--just for fun
 70.
 71.                   tabbedPane.setIconAt(n,
 72.                      new ImageIcon("red-ball.gif"));
 73.                }
 74.             }
 75.          });
 76.
 77.       JPanel buttonPanel = new JPanel();
 78.       ButtonGroup buttonGroup = new ButtonGroup();
 79.       JRadioButton wrapButton = new JRadioButton("Wrap tabs");
 80.       wrapButton.addActionListener(new
 81.          ActionListener()
 82.          {
 83.             public void actionPerformed(ActionEvent event)
 84.             {
 85.                tabbedPane.setTabLayoutPolicy(
 86.                   JTabbedPane.WRAP_TAB_LAYOUT);
 87.             }
 88.          });
 89.       buttonPanel.add(wrapButton);
 90.       buttonGroup.add(wrapButton);
 91.       wrapButton.setSelected(true);
 92.       JRadioButton scrollButton
 93.          = new JRadioButton("Scroll tabs");
 94.       scrollButton.addActionListener(new
 95.          ActionListener()
 96.          {
 97.             public void actionPerformed(ActionEvent event)
 98.             {
 99.                tabbedPane.setTabLayoutPolicy(
100.                   JTabbedPane.SCROLL_TAB_LAYOUT);
101.             }
102.          });
103.       buttonPanel.add(scrollButton);
104.       buttonGroup.add(scrollButton);
105.       getContentPane().add(buttonPanel, BorderLayout.SOUTH);
106.    }
107.
108.    private static final int WIDTH = 400;
109.    private static final int HEIGHT = 300;
110. }
111.
javax.swing.JTabbedPane

graphics/api.gif
 

Desktop Panes and Internal Frames

Many applications present information in multiple windows that are all contained inside a large frame. If you minimize the application frame, all of its windows are hidden at the same time. In the Windows environment, this user interface is sometimes called the multiple document interface or MDI. Figure 6-43 shows a typical application that utilizes this interface.

Figure 6-43. A multiple document interface application

graphics/06fig43.gif

For some time, this user interface style was very popular, but it has become less prevalent in recent years. In particular, most browsers display a separate top-level frame for each web page. (A conspicuous exception is the Opera browser, shown in Figure 6-43 ). Which is better? There are advantages and disadvantages to both approaches. MDI reduces window clutter. But having separate top-level windows means that you can use the buttons and hotkeys of the host windowing system to flip through your windows.

In the world of Java, where you can't rely on a rich host windowing system, it makes a lot of sense to have your application manage its frames.

Figure 6-44 shows a Java application with three internal frames. Two of them have decorations on the border to maximize and iconify them. The third is in its iconified state.

Figure 6-44. A Java application with three internal frames

graphics/06fig44.gif

In the Metal look and feel, the internal frames have distinctive "grabber" areas that you use to move the frames around. You can resize the windows by dragging the resize corners.

To achieve this capability, follow these steps:

  1. Use a regular JFrame window for the application.

  2. Set the content pane of the JFrame to a JDesktopPane.

    desktop = new JDesktopPane();
    setContentPane(desktop);
    
    
  3. Construct JInternalFrame windows. You can specify whether you want the icons for resizing or closing the frame. Normally, you want all icons.

    JInternalFrame iframe = new JInternalFrame(title,
       true, // resizable
       true, // closable
       true, // maximizable
       true); // iconifiable
    
    
  4. Add components to the content pane of the frame.

    iframe.getContentPane().add(c);
    
    
  5. Set a frame icon. The icon is shown in the top-left corner of the frame.

    iframe.setFrameIcon(icon);
    
    

NOTE

graphics/note.gif
 

In the current version of the Metal look and feel, the frame icon is not displayed in iconized frames.

  1. Set the size of the internal frame. As with regular frames, internal frames initially have a size of 0 by 0 pixels. Since you don't want to have all internal frames display on top of each other, you should use a variable position for the next frame. Use the reshape method to set both the position and size of the frame:

    iframe.reshape(nextFrameX, nextFrameY, width, height);
    
    
  2. As with JFrames, you need to make the frame visible.

    iframe.setVisible(true);
    
    

NOTE

graphics/note.gif
 

In earlier versions of Swing, internal frames were automatically visible and this call was not necessary.

  1. Add the frame to the JDesktopPane:

    desktop.add(iframe);
    
    
  2. You probably want to make the new frame the selected frame. Of the internal frames on the desktop, only the selected frame receives keyboard focus. In the Metal look and feel, the selected frame has a blue title bar, whereas the other frames have a gray title bar. You use the setSelected method to select a frame. However, the "selected" property can be vetoed —the currently selected frame can refuse to give up focus. In that case, the setSelected method throws a PropertyVetoException that you need to handle.

    try
    {
       iframe.setSelected(true);
    }
    catch(PropertyVetoException e)
    {
       // attempt was vetoed
    }
    
    
  3. You probably want to move the position for the next internal frame down so that it won't overlay the existing frame. A good distance between frames is the height of the title bar, which you can obtain as

    int frameDistance =
       iframe.getHeight() - iframe.getContentPane().getHeight()
    
    
  4. Use that distance to determine the next internal frame position.

    nextFrameX += frameDistance;
    nextFrameY += frameDistance;
    if (nextFrameX + width > desktop.getWidth())
       nextFrameX = 0;
    if (nextFrameY + height > desktop.getHeight())
       nextFrameY = 0;
    
    

Cascading and Tiling

In Windows, there are standard commands for cascading and tiling windows (see Figures 6-45 and 6-46 ). The Java JDesktopPane and JInternalFrame classes have no built-in support for these operations. In Example 6-18 , we show you how you can implement these operations yourself.

Figure 6-45. Cascaded internal frames

graphics/06fig45.gif

Figure 6-46. Tiled internal frames

graphics/06fig46.gif

To cascade all windows, you reshape windows to the same size and stagger their positions. The getAllFrames method of the JDesktopPane class returns an array of all internal frames.

JInternalFrame[] frames = desktop.getAllFrames();

However, you need to pay attention to the frame state. An internal frame can be in one of three states:

You use the isIcon method to find out which internal frames are currently icons and should be skipped. However, if a frame is in the maximum state, you have to first set it to be resizable by calling setMaximum(false). This is another property that can be vetoed. Therefore, you have to catch the PropertyVetoException.

The following loop cascades all internal frames on the desktop:

for (int i = 0; i < frames.length; i++)
{
   if (!frames[i].isIcon())
   {
      try
      {
         // try to make maximized frames resizable
         // this might be vetoed
         frames[i].setMaximum(false);
         frames[i].reshape(x, y, width, height);

         x += frameDistance;
         y += frameDistance;
         // wrap around at the desktop edge
         if (x + width > desktop.getWidth()) x = 0;
         if (y + height > desktop.getHeight()) y = 0;
      }
      catch(PropertyVetoException e)
      {}
   }
}

Tiling frames is trickier, particularly if the number of frames is not a perfect square. First, count the number of frames that are not icons. Then, compute the number of columns as

int cols = (int)Math.sqrt(frameCount);

Then the number of rows is

int rows = frameCount / cols;

except that the last

extra = frameCount % cols

columns have rows + 1 rows.

Here is the loop for tiling all frames on the desktop.

int width = desktop.getWidth() / cols;
int height = desktop.getHeight() / rows;
int r = 0;
int c = 0;
for (int i = 0; i < frames.length; i++)
{
   if (!frames[i].isIcon())
   {
      try
      {
         frames[i].setMaximum(false);
         frames[i].reshape(c * width,
            r * height, width, height);
         r++;
         if (r == rows)
         {
            r = 0;
            c++;
            if (c == cols - extra)
            {
               // start adding an extra row
               rows++;
               height = desktop.getHeight() / rows;
            }
         }
      }
      catch(PropertyVetoException e)
      {}
   }
}

The example program shows another common frame operation: to move the selection from the current frame to the next frame that isn't an icon. The JDesktopPane class has no method to return the selected frame. Instead, you must traverse all frames and call isSelected until you find the currently selected frame. Then, look for the next frame in the sequence that isn't an icon, and try to select it by calling

frames[next].setSelected(true);

As before, that method can throw a PropertyVetoException, in which case you keep looking. If you come back to the original frame, then no other frame was selectable, and you give up. Here is the complete loop:

for (int i = 0; i < frames.length; i++)
{
   if (frames[i].isSelected())
   {
      // find next frame that isn't an icon and can be
      // selected
      try
      {
         int next = (i + 1) % frames.length;
         while (next != i && frames[next].isIcon())
            next = (next + 1) % frames.length;
         if (next == i) return;
            // all other frames are icons
         frames[next].setSelected(true);
         frames[next].toFront();
         return;
      }
      catch(PropertyVetoException e)
      {}
   }
}

Vetoing Property Settings

Now that you have seen all these veto exceptions, you may wonder how your frames can issue a veto. The JInternalFrame class uses a general JavaBeans mechanism for monitoring the setting of properties. We discuss this mechanism in full detail in Chapter 8 . For now, we just want to show you how your frames can veto requests for property changes.

Frames don't usually want to use a veto to protest iconization or loss of focus. But it is very common for frames to check whether it is okay to close them. You close a frame with the setClosed method of the JInternalFrame class. Because the method is vetoable, it calls all registered vetoable change listeners before proceeding to make the change. That gives each of the listeners the opportunity to throw a PropertyVetoException and thereby terminate the call to setClosed before it changed any settings.

In our example program, we put up a dialog to ask the user whether it is okay to close the window (see Figure 6-47 ). If the user doesn't agree, the window stays open.

Figure 6-47. The user can veto the close property

graphics/06fig47.gif

Here is how you achieve such a notification.

  1. Add a listener object to each frame. The object must belong to some class that implements the VetoableChangeListener interface. It is best to do that right after constructing the frame. In our example, we use the frame class that constructs the internal frames. Another option would be to use an anonymous inner class.

    iframe.addVetoableChangeListener(listener);
    
    
  2. Implement the vetoableChange method, the only method required by the VetoableChangeListener interface. The method receives a PropertyChangeEvent object. Use the getName method to find the name of the property that is about to be changed (such as "closed" if the method call to veto is setClosed(true). As you will see in Chapter 8, the property name is obtained by removing the "set" prefix from the method name and changing the next letter to lowercase.

    Use the getNewValue method to get the proposed new value.

    String name = event.getPropertyName();
    Object value = event.getNewValue();
    if (name.equals("closed") && value.equals(Boolean.TRUE))
    {
       ask user for confirmation
    }
    
    
  3. Simply throw a PropertyVetoException to block the property change. Return normally if you don't want to veto the change.

    class DesktopFrame extends JFrame
       implements VetoableChangeListener
    {
       . . .
       public void vetoableChange(PropertyChangeEvent event)
          throws PropertyVetoException
       {
          . . .
          if (not ok)
             throw new PropertyVetoException("reason", event);
          // return normally if ok
       }
    }
    
    
Dialogs in internal frames

If you use internal frames, you should not use the JDialog class for dialogs. Those dialogs have two disadvantages:

Instead, for simple dialogs, use the showInternalXxxDialog methods of the JOptionPane class. They work exactly like the showXxxDialog methods, except they position a lightweight window over an internal frame.

As for more complex dialogs, construct them with a JInternalFrame. Unfortunately, then you have no built-in support for modal dialogs.

In our sample program, we use an internal dialog to ask the user whether it is okay to close a frame.

int result
   = JOptionPane.showInternalConfirmDialog(iframe,
      "OK to close?");

NOTE

graphics/note.gif
 

If you simply want to be notified when a frame is closed, then you should not use the veto mechanism. Instead, install an InternalFrameListener. An internal frame listener works just like a WindowListener. When the internal frame is closing, the internalFrameClosing method is called instead of the familiar windowClosing method. The other six internal frame notifications (opened/closed, iconified/deiconified, activated/deactivated) also correspond to the window listener methods.

Outline dragging

One criticism that developers have leveled against internal frames is that performance has not been great. By far the slowest operation is to drag a frame with complex content across the desktop. The desktop manager keeps asking the frame to repaint itself as it is being dragged, which is quite slow.

Actually, if you use Windows or X Windows with a poorly written video driver, you'll experience the same problem. Window dragging appears fast on most systems because the video hardware supports the dragging operation by mapping the image inside the frame to different screen location during the dragging process.

To improve performance without greatly degrading the user experience, you can set "outline dragging" on. When the user drags the frame, only the outline of the frame is continuously updated. The inside is repainted only when the user drops the frame to its final resting place.

To turn on outline dragging, call

desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);

This setting is the equivalent of "continuous layout" in the JSplitPane class.

NOTE

graphics/note.gif
 

In early versions of Swing, you had to use the magic incantation

desktop.putClientProperty(
   "JDesktopPane.dragMode", "outline");

to turn on outline dragging.

In the sample program, you can use the Window -> Drag Outline check box menu selection to toggle outline dragging on or off.

NOTE

graphics/note.gif
 

The internal frames on the desktop are managed by a DesktopManager class. You don't need to know about this class for normal programming. It is possible to implement different desktop behavior by installing a new desktop manager, but we won't cover that.

Example 6-18 populates a desktop with internal frames that show HTML pages. The File -> Open menu option pops up a file dialog for reading a local HTML file into a new nternal frame. If you click on any link, the linked document is displayed in another internal frame. Try out the Window -> Cascade and Window -> Tile commands. This example concludes our discussion of advanced Swing features.

Example 6-18 InternalFrameTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.io.*;
  5. import java.net.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8. import javax.swing.event.*;
  9.
 10. /**
 11.    This program demonstrates the use of internal frames.
 12. */
 13. public class InternalFrameTest
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new DesktopFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This desktop frames contains editor panes that show HTML
 25.    documents.
 26. */
 27. class DesktopFrame extends JFrame
 28. {
 29.    public DesktopFrame()
 30.    {
 31.       setTitle("InternalFrameTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       desktop = new JDesktopPane();
 35.       setContentPane(desktop);
 36.
 37.
 38.       // set up menus
 39.
 40.       JMenuBar menuBar = new JMenuBar();
 41.       setJMenuBar(menuBar);
 42.       JMenu fileMenu = new JMenu("File");
 43.       menuBar.add(fileMenu);
 44.       JMenuItem openItem = new JMenuItem("Open");
 45.       openItem.addActionListener(new
 46.          ActionListener()
 47.          {
 48.             public void actionPerformed(ActionEvent event)
 49.             {
 50.                openFile();
 51.             }
 52.          });
 53.       fileMenu.add(openItem);
 54.       JMenuItem exitItem = new JMenuItem("Exit");
 55.       exitItem.addActionListener(new
 56.          ActionListener()
 57.          {
 58.             public void actionPerformed(ActionEvent event)
 59.             {
 60.                System.exit(0);
 61.             }
 62.          });
 63.       fileMenu.add(exitItem);
 64.       JMenu windowMenu = new JMenu("Window");
 65.       menuBar.add(windowMenu);
 66.       JMenuItem nextItem = new JMenuItem("Next");
 67.       nextItem.addActionListener(new
 68.          ActionListener()
 69.          {
 70.             public void actionPerformed(ActionEvent event)
 71.             {
 72.                selectNextWindow();
 73.             }
 74.          });
 75.       windowMenu.add(nextItem);
 76.       JMenuItem cascadeItem = new JMenuItem("Cascade");
 77.       cascadeItem.addActionListener(new
 78.          ActionListener()
 79.          {
 80.             public void actionPerformed(ActionEvent event)
 81.             {
 82.                cascadeWindows();
 83.             }
 84.          });
 85.       windowMenu.add(cascadeItem);
 86.       JMenuItem tileItem = new JMenuItem("Tile");
 87.       tileItem.addActionListener(new
 88.          ActionListener()
 89.          {
 90.             public void actionPerformed(ActionEvent event)
 91.             {
 92.                tileWindows();
 93.             }
 94.          });
 95.       windowMenu.add(tileItem);
 96.       final JCheckBoxMenuItem dragOutlineItem
 97.          = new JCheckBoxMenuItem("Drag Outline");
 98.       dragOutlineItem.addActionListener(new
 99.          ActionListener()
100.          {
101.             public void actionPerformed(ActionEvent event)
102.             {
103.                desktop.setDragMode(dragOutlineItem.isSelected()
104.                   ? JDesktopPane.OUTLINE_DRAG_MODE
105.                   : JDesktopPane.LIVE_DRAG_MODE);
106.             }
107.          });
108.       windowMenu.add(dragOutlineItem);
109.    }
110.
111.    /**
112.       Creates an internal frame on the desktop.
113.       @param c the component to display in the internal frame
114.       @param t the title of the internal frame.
115.    */
116.    public void createInternalFrame(Component c, String t)
117.    {
118.       final JInternalFrame iframe = new JInternalFrame(t,
119.          true, // resizable
120.          true, // closable
121.          true, // maximizable
122.          true); // iconifiable
123.
124.       iframe.getContentPane().add(c);
125.       desktop.add(iframe);
126.
127.       iframe.setFrameIcon(new ImageIcon("document.gif"));
128.
129.       // add listener to confirm frame closing
130.       iframe.addVetoableChangeListener(new
131.          VetoableChangeListener()
132.          {
133.             public void vetoableChange(PropertyChangeEvent event)
134.                throws PropertyVetoException
135.             {
136.                String name = event.getPropertyName();
137.                Object value = event.getNewValue();
138.
139.                // we only want to check attempts to close a frame
140.                if (name.equals("closed")
141.                   && value.equals(Boolean.TRUE))
142.                {
143.                   // ask user if it is ok to close
144.                   int result
145.                      = JOptionPane.showInternalConfirmDialog(
146.                         iframe, "OK to close?");
147.
148.                   // if the user doesn't agree, veto the close
149.                   if (result != JOptionPane.YES_OPTION)
150.                      throw new PropertyVetoException(
151.                         "User canceled close", event);
152.                }
153.            }
154.          });
155.
156.       // position frame
157.       int width = desktop.getWidth() / 2;
158.       int height = desktop.getHeight() / 2;
159.       iframe.reshape(nextFrameX, nextFrameY, width, height);
160.
161.       iframe.show();
162.
163.       // select the frame--might be vetoed
164.       try
165.       {
166.          iframe.setSelected(true);
167.       }
168.       catch(PropertyVetoException e)
169.       {}
170.
171.       /* if this is the first time, compute distance between
172.          cascaded frames
173.       */
174.
175.       if (frameDistance == 0)
176.          frameDistance = iframe.getHeight()
177.             - iframe.getContentPane().getHeight();
178.
179.       // compute placement for next frame
180.
181.       nextFrameX += frameDistance;
182.       nextFrameY += frameDistance;
183.       if (nextFrameX + width > desktop.getWidth())
184.          nextFrameX = 0;
185.       if (nextFrameY + height > desktop.getHeight())
186.          nextFrameY = 0;
187.    }
188.
189.    /**
190.       Cascades the non-iconified internal frames of the desktop.
191.    */
192.    public void cascadeWindows()
193.    {
194.       JInternalFrame[] frames = desktop.getAllFrames();
195.       int x = 0;
196.       int y = 0;
197.       int width = desktop.getWidth() / 2;
198.       int height = desktop.getHeight() / 2;
199.
200.       for (int i = 0; i < frames.length; i++)
201.       {
202.          if (!frames[i].isIcon())
203.          {
204.             try
205.             {
206.                // try to make maximized frames resizable
207.                // this might be vetoed
208.                frames[i].setMaximum(false);
209.                frames[i].reshape(x, y, width, height);
210.
211.                x += frameDistance;
212.                y += frameDistance;
213.                // wrap around at the desktop edge
214.                if (x + width > desktop.getWidth()) x = 0;
215.                if (y + height > desktop.getHeight()) y = 0;
216.             }
217.             catch(PropertyVetoException e)
218.             {}
219.          }
220.       }
221.    }
222.
223.    /**
224.       Tiles the non-iconified internal frames of the desktop.
225.    */
226.    public void tileWindows()
227.    {
228.       JInternalFrame[] frames = desktop.getAllFrames();
229.
230.       // count frames that aren't iconized
231.       int frameCount = 0;
232.       for (int i = 0; i < frames.length; i++)
233.       {
234.          if (!frames[i].isIcon())
235.             frameCount++;
236.       }
237.
238.       int rows = (int)Math.sqrt(frameCount);
239.       int cols = frameCount / rows;
240.       int extra = frameCount % rows;
241.          // number of columns with an extra row
242.
243.       int width = desktop.getWidth() / cols;
244.       int height = desktop.getHeight() / rows;
245.       int r = 0;
246.       int c = 0;
247.       for (int i = 0; i < frames.length; i++)
248.       {
249.          if (!frames[i].isIcon())
250.          {
251.             try
252.             {
253.                frames[i].setMaximum(false);
254.                frames[i].reshape(c * width,
255.                   r * height, width, height);
256.                r++;
257.                if (r == rows)
258.                {
259.                   r = 0;
260.                   c++;
261.                   if (c == cols - extra)
262.                   {
263.                      // start adding an extra row
264.                      rows++;
265.                      height = desktop.getHeight() / rows;
266.                   }
267.                }
268.             }
269.             catch(PropertyVetoException e)
270.             {}
271.          }
272.       }
273.    }
274.
275.    /**
276.       Brings the next non-iconified internal frame to the front.
277.    */
278.    public void selectNextWindow()
279.    {
280.       JInternalFrame[] frames = desktop.getAllFrames();
281.       for (int i = 0; i < frames.length; i++)
282.       {
283.          if (frames[i].isSelected())
284.          {
285.             // find next frame that isn't an icon and can be
286.             // selected
287.             try
288.             {
289.                int next = (i + 1) % frames.length;
290.                while (next != i && frames[next].isIcon())
291.                   next = (next + 1) % frames.length;
292.                if (next == i) return;
293.                   // all other frames are icons or veto selection
294.                frames[next].setSelected(true);
295.                frames[next].toFront();
296.                return;
297.             }
298.             catch(PropertyVetoException e)
299.             {}
300.          }
301.       }
302.    }
303.
304.    /**
305.       Asks the user to open an HTML file.
306.    */
307.    public void openFile()
308.    {
309.       // let user select file
310.
311.       JFileChooser chooser = new JFileChooser();
312.       chooser.setCurrentDirectory(new File("."));
313.       chooser.setFileFilter(new
314.          javax.swing.filechooser.FileFilter()
315.          {
316.             public boolean accept(File f)
317.             {
318.                String fname = f.getName().toLowerCase();
319.                return fname.endsWith(".html")
320.                   || fname.endsWith(".htm")
321.                   || f.isDirectory();
322.             }
323.             public String getDescription()
324.             {
325.                return "HTML Files";
326.             }
327.          });
328.       int r = chooser.showOpenDialog(this);
329.
330.       if (r == JFileChooser.APPROVE_OPTION)
331.       {
332.          // open the file that the user selected
333.
334.          String filename = chooser.getSelectedFile().getPath();
335.          try
336.          {
337.             URL fileUrl = new URL("file:" + filename);
338.             createInternalFrame(createEditorPane(fileUrl),
339.                filename);
340.          }
341.          catch(MalformedURLException e)
342.          {
343.          }
344.       }
345.    }
346.
347.    /**
348.       Creates an editor pane.
349.       @param u the URL of the HTML document
350.    */
351.    public Component createEditorPane(URL u)
352.    {
353.       // create an editor pane that follows hyperlink clicks
354.
355.       JEditorPane editorPane = new JEditorPane();
356.       editorPane.setEditable(false);
357.       editorPane.addHyperlinkListener(new
358.          HyperlinkListener()
359.          {
360.             public void hyperlinkUpdate(HyperlinkEvent event)
361.             {
362.                if (event.getEventType()
363.                   == HyperlinkEvent.EventType.ACTIVATED)
364.                   createInternalFrame(createEditorPane(
365.                      event.getURL()), event.getURL().toString());
366.             }
367.          });
368.       try
369.       {
370.          editorPane.setPage(u);
371.       }
372.       catch(IOException e)
373.       {
374.          editorPane.setText("Exception: " + e);
375.       }
376.       return new JScrollPane(editorPane);
377.    }
378.
379.    private JDesktopPane desktop;
380.    private int nextFrameX;
381.    private int nextFrameY;
382.    private int frameDistance;
383.
384.    private static final int WIDTH = 600;
385.    private static final int HEIGHT = 400;
386. }
javax.swing.JDesktopPane

graphics/api.gif
 

javax.swing.JInternalFrame

graphics/api.gif
 

javax.swing.JComponent

graphics/api.gif
 

java.beans.VetoableChangeListener

graphics/api.gif
 

java.beans.PropertyChangeEvent

graphics/api.gif
 

java.beans.PropertyVetoException

graphics/api.gif
 

CONTENTS